kdlog.gd

kdlog.gd is a very naive logger I use in most of my godot projects. the general idea is that you can add it to your project as a Global (and name it whatever you want). Then instead of using godot's print() you use RLog.print() (where RLog is whatever you named it) for identical behaviour.

However, each RLog.print() call can have an id attached to it, which is where this gets interesting. the default id is always, which always prints. if you add your own IDs, they won't show up unless you use RLog.add_layer to add it. now you can pepper a script with logs, and toggle them on and off by id.

I use this to load my game up with logs that I need to debug a system, then just turn them all off at some root. kdlog.gd automatically color codes them, but you can provide your own tag when you add the layer to override that functionality.

⚠️ There's a performance hit here: with no layers, your print() calls still need to fail a Array.has() call for their ID. honestly though, its worth it for the convenience while building. Just stick an immediate return into the print() function and the cost should still be micro (depending on your version of "micro - GDScript is still an interpreted language). I'll measure it if it ever seems like it will matter to me (unlikely).

Some logs

Find it here

extends Node

var layers:Array[String]

var tags:Dictionary[String,String]

static var ALWAYS = "always"

var all_colors:Array = [
	"aqua",
	"black",
	"blue",
	"fuchsia",
	"gray",
	"green",
	"lime",
	"maroon",
	"navy",
	"purple",
	"red",
	"teal",
	"white",
	"yellow"
]

func _ready():
	add_layer(ALWAYS, "[b] %s [/b]")
	
func add_layer(layer_name:String, tag:String = ""):
	if layers.has(layer_name):
		return
		
	layers.append(layer_name)
	if tag.is_empty():
		#generate color tag
		tags[layer_name] = generate_color_tag(layer_name)
	else:
		tags[layer_name] = tag
		
func print(msg, id:StringName = ALWAYS):
	if not layers.has(id):
		return
		
	if not tags.has(id):
		tags[id] = generate_color_tag(id)
	
	print_rich(tags[id] % msg)
	
func generate_color_tag(id:StringName)->String:
	var color = random_color(id)
	var color_tag = "[color=%s] %s [/color]" % [color, "%s"]
	return color_tag
	
	
func random_color(id:StringName)->String:
	var rng = RandomNumberGenerator.new()
	rng.seed = hash(id)
	var index = rng.randi_range(0,all_colors.size()-1)
	return all_colors[index]

Mastodon

This article was updated on