-
Notifications
You must be signed in to change notification settings - Fork 1
Saving logs to a file
To save logs to a file, first you should disable all pretty prints for your subscriber using the barebones
method on TraceSubscriber
var file_logger = (
TraceSubscriber
. new()
. barebones()
)
Next, create a custom writer that takes a log message and writes it to a file. A writer is simply a function object that takes a string as a parameter and does something with it.
# Open a file for writing
var logs = FileAccess.open("res://examples/test/logs.txt", FileAccess.WRITE)
# Create a writer
var writer = func(msg: String) -> void:
logs.store_string(text + "\n")
Or, better yet, use the provided TraceSubscriber.writer_from_file
method that does the same thing
# Open a file for writing
var logs = FileAccess.open("res://examples/test/logs.txt", FileAccess.WRITE)
# Create a writer
var writer = TraceSubscriber.writer_from_file(logs)
Then, use the with_writer
method to set the custom writer
# Build a subscriber that writes to a file
var file_logger = (
TraceSubscriber
. new()
. barebones()
. with_writer(writer)
)
# Initialize the subscriber
file_logger.init()
logs.txt:
[2023-11-02T12:59:47] INFO examples/test/test.gd::_ready: Game Started!
[2023-11-02T12:59:47] DEBUG examples/test/test.gd::_ready: Initializing systems... 🧙♂️
[2023-11-02T12:59:47] WARN examples/test/test.gd::_ready: Cannot find file 'data.json' 🤔
[2023-11-02T12:59:47] ERROR examples/test/test.gd::_ready: Cannot communicate with server 😱
Since you can provide your own writers, There's nothing stopping you from creating a writer that sends logs to a server or a writer that does absolutely nothing or a writer that collects logs and starts up your printer and prints them to paper. This should provide you with the flexibility to fit Tracer
to your needs.