Skip to content

Commit e4ca4bf

Browse files
author
toasteater
authored
Merge pull request #29 from jacobsky/logging_recipe
Added Logging Recipe
2 parents 68c2c6c + 9d4ef6f commit e4ca4bf

File tree

1 file changed

+209
-0
lines changed

1 file changed

+209
-0
lines changed

src/recipes/logging.md

Lines changed: 209 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,209 @@
1+
# Logging
2+
3+
Logging in Godot can be accessed by using the `godot_print!`, `godot_warn!`, and `godot_error!` macros.
4+
5+
These macros only work when the library is loaded by Godot. They will panic instead when invoked outside that context, for example, when the crate is being tested with cargo test
6+
7+
## Simple wrapper macros for test configurations
8+
9+
The first option that you have is wrap the `godot_print!` macros in the following macro that will use `godot_print!` when running with Godot, and stdout when run during tests.
10+
11+
```rust
12+
/// prints to Godot's console, except in tests, there it prints to stdout
13+
macro_rules! console_print {
14+
($($args:tt)*) => ({
15+
if cfg!(test) {
16+
println!($($args)*);
17+
} else {
18+
gdnative::godot_print!($($args)*);
19+
}
20+
});
21+
}
22+
```
23+
24+
## Using a logging Crate
25+
26+
A more robust solution is to integrate an existing logging library.
27+
28+
This recipe demonstrates using the `log` crate with `flexi-logger`. While most of this guide will work with other backends, the initialization and `LogWriter` implementation may differ.
29+
30+
First add the following crates to your `Cargo.toml` file. You may want to check the crates.io pages of the crates for any updates.
31+
32+
```toml
33+
log = "0.4.14"
34+
flexi_logger = "0.17.1"
35+
```
36+
37+
Then, write some code that glues the logging crates with Godot's logging interface. `flexi-logger`, for example, requires a `LogWriter` implementation:
38+
39+
```rust
40+
use gdnative::prelude::*;
41+
use flexi_logger::writers::LogWriter;
42+
use flexi_logger::{DeferredNow, Record};
43+
use log::{Level, LevelFilter};
44+
45+
pub struct GodotLogWriter {}
46+
47+
impl LogWriter for GodotLogWriter {
48+
fn write(&self, _now: &mut DeferredNow, record: &Record) -> std::io::Result<()> {
49+
match record.level() {
50+
// Optionally push the Warnings to the godot_error! macro to display as an error in the Godot editor.
51+
flexi_logger::Level::Error => godot_error!("{}:{} -- {}", record.level(), record.target(), record.args()),
52+
// Optionally push the Warnings to the godot_warn! macro to display as a warning in the Godot editor.
53+
flexi_logger::Level::Warn => godot_warn!("{}:{} -- {}",record.level(), record.target(), record.args()),
54+
_ => godot_print!("{}:{} -- {}", record.level(), record.target(), record.args())
55+
} ;
56+
Ok(())
57+
}
58+
59+
fn flush(&self) -> std::io::Result<()> {
60+
Ok(())
61+
}
62+
63+
fn max_log_level(&self) -> LevelFilter {
64+
LevelFilter::Trace
65+
}
66+
}
67+
```
68+
69+
For the logger setup, place the code logger configuration code in your `fn init(handle: InitHandle)` as follows.
70+
71+
To add the logging configuration, you need to add the initial configuration and start the logger inside the init function.
72+
```rust
73+
fn init(handle: InitHandle) {
74+
flexi_logger::Logger::with_str("trace")
75+
.log_target(flexi_logger::LogTarget::Writer(Box::new(crate::util::GodotLogWriter {})))
76+
.start()
77+
.expect("the logger should start");
78+
/* other initialization work goes here */
79+
}
80+
godot_init!(init);
81+
```
82+
83+
### Setting up a log target for tests
84+
When running in a test configuration, if you would like logging functionality, you will need to initialize a log target.
85+
86+
As tests are run in parallel, it will be necessary to use something like the following code to initialize the logger only once. The `#[cfg(test)]` attributes are used to ensure that this code is not accessible outside of test builds.
87+
88+
Place this in your crate root (usually lib.rs)
89+
90+
```rust
91+
#[cfg(test)]
92+
use std::sync::Once;
93+
#[cfg(test)]
94+
static TEST_LOGGER_INIT: Once = Once::new();
95+
#[cfg(test)]
96+
fn test_setup_logger() {
97+
TEST_LOGGER_INIT.call_once(||{
98+
flexi_logger::Logger::with_str("debug")
99+
.log_target(flexi_logger::LogTarget::StdOut)
100+
.start()
101+
.expect("the logger should start");
102+
});
103+
}
104+
```
105+
106+
You can call the above code in your units tests with `crate::test_setup_logger()`. Please note: currently there does not appear to be a tes case that will be called before tests are configured, so the `test_setup_logger` will need to be called in every test where you require log output.
107+
108+
Now that the logging is configured, you can use use it in your code such as in the following sample
109+
```rust
110+
log::trace!("trace message: {}", "message string");
111+
log::debug!("debug message: {}", "message string");
112+
log::info!("info message: {}", "message string");
113+
log::warn!("warning message: {}", "message string");
114+
log::error!("error message: {}", "message string");
115+
```
116+
117+
At this point, we have a logging solution implemented for our Rust based code that will pipe the log messages to Godot.
118+
119+
But what about GDScript? It would be nice to have consistent log messages in both GDScript and GDNative. One way to ensure that is to expose the logging functionality to Godot with a `NativeClass`.
120+
121+
### Exposing to GDScript
122+
123+
> ### Note
124+
> As the rust macros cannot get the GDScript name or resource_path, it is necessary to pass the log target from GDScript.
125+
126+
```rust
127+
#[derive(NativeClass, Copy, Clone, Default)]
128+
#[user_data(Aether<DebugLogger>)]
129+
#[inherit(Node)]
130+
pub struct DebugLogger;
131+
132+
#[methods]
133+
impl DebugLogger {
134+
fn new(_: &Node) -> Self {
135+
Self {}
136+
}
137+
#[export]
138+
fn error(&self, _owner: &Node, target: String, message: String) {
139+
log::error!(target: &target, "{}", message);
140+
}
141+
#[export]
142+
fn warn(&self, _: &Node, target: String, message: String) {
143+
log::warn!(target: &target, "{}", message);
144+
}
145+
#[export]
146+
fn info(&self, _: &Node, target: String, message: String) {
147+
log::info!(target: &target, "{}", message);
148+
}
149+
#[export]
150+
fn debug(&self, _: &Node, target: String, message: String) {
151+
log::debug!(target: &target, "{}", message);
152+
}
153+
#[export]
154+
fn trace(&self, _: &Node, target: String, message: String) {
155+
log::trace!(target: &target, "{}", message);
156+
}
157+
}
158+
```
159+
160+
After adding the class above with `handle.add_class::<DebugLogger>()` in the `init` function, you may add it as an Autoload Singleton in your project for easy access. In the example below, the name "game_logger" is chosen for the Autoload singleton:
161+
162+
```gdscript
163+
game_logger.trace("name_of_script.gd", "this is a trace message")
164+
game_logger.debug("name_of_script.gd", "this is a debug message")
165+
game_logger.info("name_of_script.gd", "this is an info message")
166+
game_logger.warn("name_of_script.gd", "this is a warning message")
167+
game_logger.error("name_of_script.gd", "this is an error message")
168+
```
169+
170+
As this is not very ergonomic, it is possible to make a more convenient access point that you can use in your scripts. To make the interface closer to the Rust one, we can create a `Logger` class in GDScript that will call the global methods with the name of our script class.
171+
172+
```gdscript
173+
extends Reference
174+
175+
class_name Logger
176+
177+
var _script_name
178+
179+
func _init(script_name: String) -> void:
180+
self._script_name = script_name
181+
182+
func trace(msg: String) -> void:
183+
D.trace(self._script_name, msg)
184+
185+
func debug(msg: String) -> void:
186+
D.debug(self._script_name, msg)
187+
188+
func info(msg: String) -> void:
189+
D.info(self._script_name, msg)
190+
191+
func warn(msg: String) -> void:
192+
D.warn(self._script_name, msg)
193+
194+
func error(msg: String) -> void:
195+
D.error(self._script_name, msg)
196+
```
197+
198+
To use the above class, create an instance of `Logger` in a local variable with the desired `script_name` and use it as in the script example below:
199+
200+
```gdscript
201+
extends Node
202+
203+
var logger = Logger.new("script_name.gd")
204+
205+
func _ready() -> void:
206+
logger.info("_ready")
207+
```
208+
209+
And now you have a logging solution fully implemented in Rust and usable in GDScript.

0 commit comments

Comments
 (0)