Logging in GDScript

Here’s the translation of the Go logging example to GDScript, formatted in Markdown suitable for Hugo:

Our example demonstrates various logging techniques in GDScript. Here’s the full source code:

extends Node

func _ready():
    # Simple print statement, which is the most basic form of logging in GDScript
    print("standard logger")

    # GDScript doesn't have built-in microsecond precision, but we can use OS.get_ticks_msec()
    print("with milliseconds: %d" % OS.get_ticks_msec())

    # To include file and line information, we can use get_stack()
    var stack = get_stack()
    var frame = stack[0]
    print("with file/line: %s:%s" % [frame.source, frame.line])

    # Custom loggers can be created as separate functions
    func my_log(message):
        print("my: %s" % message)

    my_log("from mylog")

    # Changing the prefix of our custom logger
    func oh_my_log(message):
        print("ohmy: %s" % message)

    oh_my_log("from mylog")

    # Logging to a file
    var file = File.new()
    file.open("user://log.txt", File.WRITE)
    file.store_string("buf: hello\n")
    file.close()

    # Reading and printing the file content
    file.open("user://log.txt", File.READ)
    print("from buflog: %s" % file.get_as_text())
    file.close()

    # GDScript doesn't have built-in structured logging, but we can create a simple version
    func log_json(message, data = {}):
        var time = OS.get_datetime()
        var log_data = {
            "time": "%04d-%02d-%02dT%02d:%02d:%02d" % [time.year, time.month, time.day, time.hour, time.minute, time.second],
            "level": "INFO",
            "msg": message
        }
        log_data.merge(data)
        print(JSON.print(log_data))

    log_json("hi there")
    log_json("hello again", {"key": "val", "age": 25})

To run the program, save this script as Logging.gd and attach it to a Node in your Godot scene.

Sample output; the date, time, and milliseconds emitted will depend on when the example ran:

standard logger
with milliseconds: 12345
with file/line: res://Logging.gd:11
my: from mylog
ohmy: from mylog
from buflog: buf: hello

{"time":"2023-08-22T10:45:16","level":"INFO","msg":"hi there"}
{"time":"2023-08-22T10:45:16","level":"INFO","msg":"hello again","key":"val","age":25}

This example demonstrates various logging techniques in GDScript:

  1. Basic printing with print().
  2. Including millisecond precision using OS.get_ticks_msec().
  3. Including file and line information using get_stack().
  4. Creating custom logging functions.
  5. Writing logs to a file using the File class.
  6. A simple implementation of structured logging using dictionaries and JSON.

Note that GDScript doesn’t have built-in logging libraries like Go’s log and slog packages. However, we can create similar functionality using GDScript’s built-in features and the File class for file I/O operations.