Giter Club home page Giter Club logo

godotlogger's Introduction

GodotLogger

JSON-formatted logger

Settings

var CURRENT_LOG_LEVEL=LogLevel.INFO
var write_logs:bool = false
var log_path:String = "res://game.log"

Command line args

Provide these to your command line if you want to override defaults

log-level=error
use-isotime=true

Singletons

GodotLogger

  • GodotLogger.debug(msg,data)
  • GodotLogger.info(msg,data)
  • GodotLogger.warn(msg,data)
  • GodotLogger.error(msg,data)
  • GodotLogger.fatal(msg,data)

Classes

Log

Is the class implementation of the singleton logger. The CURRENT_LOG_LEVEL can be set to any of the following levels:

enum LogLevel {
	DEBUG,
	INFO,
	WARN,
	ERROR,
	FATAL,
}

When it is set anything less than the current log level will be filtered out

JsonData

Methods

  • marshal(obj:Object,compact:bool=false,compressMode:int=-1,skip_whitelist:bool=false) -> PackedByteArray:

  • unmarshal(dict:Dictionary,obj:Object,compressMode:int=-1) -> bool:

  • unmarshal_bytes_to_dict(data:PackedByteArray,compressMode:int=-1) -> Dictionary:

  • unmarshal_bytes(data:PackedByteArray,obj:Object,compressMode:int=-1) -> bool:

  • to_dict(obj:Object,compact:bool,skip_whitelist:bool=false) ->Dictionary:

Config

Will get either flags or env vars for the program and return the value or the default value.

Methods

  • get_var(name,default=""):

  • get_int(name,default=0) -> int:

  • get_bool(name,default=false,prefix:String="") -> bool:

  • get_custom_var(name,type,default=null):

godotlogger's People

Contributors

seann-moser avatar jimmyloar avatar chrisknyfe avatar admincrystal avatar cstaaben avatar loufe avatar

Stargazers

 avatar  avatar  avatar Tim Oliver avatar Michael avatar Francesco Camarlinghi avatar  avatar  avatar Russell Matney avatar George Stavrinos avatar  avatar BlockImperium avatar Sam Biggins avatar Chris Buckett avatar Luca Talevi avatar  avatar Satsuki Akiba avatar Kyle Harrison avatar  avatar Paul McNamee avatar  avatar  avatar David Kincaid avatar Greg avatar  avatar  avatar Jack Kester avatar 热心市民张学徒 avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

godotlogger's Issues

Release mode & CallSite tweaks

Hi,
Nice library, just what I'm looking for.

I've made a couple of minor tweaks that you may want to incorporate into future releases.

1. MIN_LEVEL_RELEASE_MODE

This sets a minimum log level when not running in debug mode (Export with Debug flag deselected).
Basically, it allows forcing the log level to something higher than you might have when running in debug mode (eg, only ERROR or FATAL).
My hacky implementation below...

#logger.gd
var MIN_LEVEL_RELEASE_MODE = "error"
func _set_loglevel(level:String):
    if OS.is_debug_build() == false:
        level = MIN_LEVEL_RELEASE_MODE

2. Adding call-site information to the log output (eg filename:function:line_no).

Again, a hacky solution to get the stack and output the line that called GodotLogger.info() (or .debug or whatever).
No performance testing what so ever... (I don't know what the performance implications of calling get_stack() are, but I don't expect it'd be good...

Output is something like:
INFO [22/11/2023 07:03:21][my_level.gd:generate_level:123] Generated Room: 0

#logger.gd
func _return_callsite_from_stack(stack) -> String:
	if stack == null: # null in release mode
		return "" 

	if stack.size() < 3: # just to be sure
		return ""

	var callsite = stack[2] # third item in the stack is where it was called from
	var format_str = "[{file}:{func}:{line}]"
	var callsite_file_split = callsite.source.rsplit("/") # just get the filename to save chars on the logging line
	return format_str.format({
		"file": callsite_file_split[callsite_file_split.size() -1],
		"func": callsite.function,
		"line": callsite.line,
	})

#existing func
func logger(message:String,values,log_level=LogLevel.INFO):
	if CURRENT_LOG_LEVEL > log_level :
		return
	var log_msg_format = "{level} [{time}]{call_site}{prefix} {message} " #added {call_site}

	var now = Time.get_datetime_dict_from_system(true)

	var msg = log_msg_format.format(
		{
			"prefix":_prefix,
			"message":message,
			"time":"{day}/{month}/{year} {hour}:{minute}:{second}".format(now),
			"level":LogLevel.keys()[log_level],
			"call_site": _return_callsite_from_stack(get_stack()) # populate call_site
		})

Hope someone finds that useful :)

Logged dictionaries don't preserve key and value types

When logging ints, floats, booleans and null, their types are not preserved and instead they are converted to strings.

This code:

class InventoryItem extends Resource:
	@export var itemtype: int = 0
	@export var metadata: Dictionary = {}
	@export var quantity: int = 1


func _ready():
	var d = {
		"foobar": "bazqux",
		5: 25,
		3.14: 12e3,
		true: false,
		null: null,
		"an object": InventoryItem.new(),
	}
	GodotLogger.info("this is an array", d)

results in the following output:
INFO [21/9/2023 22:57:53] this is an array {"foobar":"bazqux","5":"25","3.14":"12000","true":"false","<null>":"<null>","an object":"{"itemtype":0,"metadata":{},"quantity":1,"resource_local_to_scene":false,"resource_name":"","resource_path":""}"}

Logging null prevents line from being printed

Logging a null prevents the line from being printed. Any null object or array also results in the line not printing. Is that intended behavior? I would prefer that a log line prints even if the value I pass is null.

The following line prints nothing:
GodotLogger.info("this is a null", null)

Logged arrays print invalid JSON

Arrays are not being logged correctly (I mean to say, aren't valid json) - strings end up missing quotes, the brackets are replaced with curly braces, there are no commas, and nulls show up as <null>.

GodotLogger.info("this is an array", ["foobar", 5, 3.14, false, null])

results in

INFO [21/9/2023 22:42:34] this is an array {foobar53.14false<null}

Emit a signal that is emitted when message is logged.

I'm implementing an external log window for when my project runs without the editor, and would like to use your addon for my logging needs. But in order for the log window to pick up the messages sent to the log messages a signal would be in order. I can of course just add it to my instance of the addon, but thought it would be something that more people would benefit from. Would you mind me adding this to your addon?

Stack trace included on debug logs is static

Summary

The stack trace included on all logs coming from GodotLogger.debug() is always: At: res://addons/logger/logger.gd:95:logger()

Expected Behavior

The stack trace on debug level logs should reflect the point at which the call to debug() took place.

License mismatch: MIT or GPL-3?

The Godot Asset Library lists your asset as MIT licensed, but this Github repo's LICENSE file says it's GPL-3.0. While both are open source, these two licenses are very different, as one is copyleft and the other is permissive. Please clarify which license you really want:

  • If you want to make sure anyone who uses this code must make their Godot game's source code available also under GPL-3.0 or compatible license, please update the Godot Asset Library and list it as GPL-3.0 (or remove it from the Asset Library).

  • If you want people to have maximum freedom, in your next version please update the LICENSE file of this Github repo to the MIT license text.

Memory leak when using GodotLogger.with()

Whenever GodotLogger.with() is used, an orphan node is created, leading to a (small) memory leak

Here is a patch that fixed the issue for me :

diff --git a/addons/logger/logger.gd b/addons/logger/logger.gd
index 4b8ee65b1..db4feef3d 100644
--- a/addons/logger/logger.gd
+++ b/addons/logger/logger.gd
@@ -44,12 +44,10 @@ func _set_loglevel(level:String):
 			CURRENT_LOG_LEVEL = LogLevel.FATAL
 
 func with(prefix:String="",args:Dictionary={}) ->Log :
-	var l = Log.new()
-	l.CURRENT_LOG_LEVEL = self.CURRENT_LOG_LEVEL
-	l._prefix = prefix
+	self._prefix = prefix
 	for k in args:
-		l._default_args[k] = args[k]
-	return l
+		self._default_args[k] = args[k]
+	return self
 
 func logger(message:String,values,log_level=LogLevel.INFO):
 	if CURRENT_LOG_LEVEL > log_level :

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.