logging.odin 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #+private
  2. package testing
  3. /*
  4. (c) Copyright 2024 Feoramund <[email protected]>.
  5. Made available under Odin's BSD-3 license.
  6. List of contributors:
  7. Ginger Bill: Initial implementation.
  8. Feoramund: Total rewrite.
  9. */
  10. import "base:runtime"
  11. import "core:fmt"
  12. import "core:log"
  13. import "core:strings"
  14. import "core:sync/chan"
  15. import "core:time"
  16. when USING_SHORT_LOGS {
  17. Default_Test_Logger_Opts :: runtime.Logger_Options {
  18. .Level,
  19. .Terminal_Color,
  20. .Short_File_Path,
  21. .Line,
  22. }
  23. } else {
  24. Default_Test_Logger_Opts :: runtime.Logger_Options {
  25. .Level,
  26. .Terminal_Color,
  27. .Short_File_Path,
  28. .Line,
  29. .Procedure,
  30. .Date, .Time,
  31. }
  32. }
  33. Log_Message :: struct {
  34. level: runtime.Logger_Level,
  35. text: string,
  36. time: time.Time,
  37. // `text` may be allocated differently, depending on where a log message
  38. // originates from.
  39. allocator: runtime.Allocator,
  40. }
  41. test_logger_proc :: proc(logger_data: rawptr, level: runtime.Logger_Level, text: string, options: runtime.Logger_Options, location := #caller_location) {
  42. t := cast(^T)logger_data
  43. if level >= .Error {
  44. t.error_count += 1
  45. }
  46. cloned_text, clone_error := strings.clone(text, t._log_allocator)
  47. assert(clone_error == nil, "Error while cloning string in test thread logger proc.")
  48. now := time.now()
  49. chan.send(t.channel, Event_Log_Message {
  50. level = level,
  51. text = cloned_text,
  52. time = now,
  53. formatted_text = format_log_text(level, text, options, location, now, t._log_allocator),
  54. })
  55. }
  56. runner_logger_proc :: proc(logger_data: rawptr, level: runtime.Logger_Level, text: string, options: runtime.Logger_Options, location := #caller_location) {
  57. log_messages := cast(^[dynamic]Log_Message)logger_data
  58. now := time.now()
  59. append(log_messages, Log_Message {
  60. level = level,
  61. text = format_log_text(level, text, options, location, now),
  62. time = now,
  63. allocator = context.allocator,
  64. })
  65. }
  66. format_log_text :: proc(level: runtime.Logger_Level, text: string, options: runtime.Logger_Options, location: runtime.Source_Code_Location, at_time: time.Time, allocator := context.allocator) -> string{
  67. backing: [1024]byte
  68. buf := strings.builder_from_bytes(backing[:])
  69. log.do_level_header(options, &buf, level)
  70. log.do_time_header(options, &buf, at_time)
  71. log.do_location_header(options, &buf, location)
  72. return fmt.aprintf("%s%s", strings.to_string(buf), text, allocator = allocator)
  73. }