Godot中自定义日志打印

default

创建 Log.gd 脚本

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# Logger.gd
extends Node

# 日志级别枚举
enum LOG_LEVEL {
	DEBUG = 0,
	INFO = 1,
	WARNING = 2,
	ERROR = 3
}

# 配置变量
var current_log_level: LOG_LEVEL = LOG_LEVEL.DEBUG
var enable_file_logging: bool = false
var log_file_path: String = "user://log.log"

func _init():
	info("日志等级:%s,是否开启日志文件:%s,日志文件路径:%s" % [current_log_level, enable_file_logging, log_file_path])

## debug日志
func debug(message: String) -> void:
	_log(message, LOG_LEVEL.DEBUG)

## info日志
func info(message: String) -> void:
	_log(message, LOG_LEVEL.INFO)

func warning(message: String) -> void:
	_log(message, LOG_LEVEL.WARNING)

func error(message: String) -> void:
	_log(message, LOG_LEVEL.ERROR)


# 内部日志处理方法
func _log(message: String, level: LOG_LEVEL) -> void:
	if level<current_log_level:
		return
		
	message = _handle(message)
		
	var level_name = LOG_LEVEL.get(level)
	var time = Time.get_time_dict_from_system()
	var timestamp = "%02d:%02d:%02d" % [time.hour, time.minute, time.second]
	var formatted_message = "[%s]-[%s]: %s" % [timestamp, level, message]
	
	# 输出到控制台
	_print_to_console(formatted_message, level)
	
	# 输出到文件
	if enable_file_logging:
		_write_to_file(formatted_message)

static var user_path = "user://"
static var absolute_user_path = ProjectSettings.globalize_path("user://")
func _handle(msg: String) -> String:
	if msg.contains(user_path):
		msg = msg.replace(user_path, absolute_user_path)
	return msg

# 控制台输出带颜色
func _print_to_console(message: String, level: LOG_LEVEL) -> void:
	var color = "white"
	match level:
		LOG_LEVEL.DEBUG:
			color = "cyan"
		LOG_LEVEL.INFO:
			color = "white"
		LOG_LEVEL.WARNING:
			color = "yellow"
		LOG_LEVEL.ERROR:
			color = "red"
	print_rich("[color=%s]%s[/color]" % [color, message])

# 文件日志
func _write_to_file(message: String) -> void:
	var file = FileAccess.open(log_file_path, FileAccess.READ_WRITE)
	if file:
		file.seek_end()
		file.store_string(message + "\n")
		file.close()
	else:
		push_error("Failed to open log file: " + log_file_path)

加入自动加载

项目-项目设置-全局-自动加载-选取文件-添加-关闭

使用日志

1
2
Log.info("保存成功")
Log.error("配置保存失败")
Licensed under CC BY-NC-SA 4.0
Gear(夕照)的博客。记录开发、生活,以及一些不足为道的思考……