basic/trace.rs
1use afire::{
2 trace,
3 trace::{set_log_level, Level},
4 Method, Response, Server,
5};
6
7use crate::Example;
8
9// You can run this example with `cargo run --example basic -- trace`
10
11// In this example we will learn about afire's built-in tracing system.
12// Because of how its used internally there is a global log level, not one per server.
13// You can set this level with `afire::trace::set_log_level`, which takes one parameter a `afire::trace::Level`.
14// You can also set wether the logs have ANSI codes for color using `afire::trace::set_log_color`, color is enabled by default.
15// Now to use the logger there is the `trace!` macro, which you can use one of two different ways:
16//
17// trace!(Level::<LOG_LEVEL>, <FORMATTED ARGS>)
18// trace!(<FORMATTED ARGS>) // uses the Trace level
19//
20// // Examples
21// let a = 100;
22// trace!("The var a is currently {a}");
23// trace!(Level::Error, "An error occurred!");
24//
25// The Log Levels are in the following order, with the more verbose levels at the bottom.
26// Setting the log level to Off will disable all logging.
27// Also note that Error is the default level.
28//
29// - Off
30// - Error
31// - Trace
32// - Debug
33
34pub struct Trace;
35
36impl Example for Trace {
37 fn name(&self) -> &'static str {
38 "trace"
39 }
40
41 fn exec(&self) {
42 // Set the log level to Trace (shows some helpful information during startup)
43 // The default is Level::Error
44 set_log_level(Level::Trace);
45 trace!(Level::Trace, "Setting log level to Trace");
46 trace!(Level::Error, "Example error message");
47
48 // Create a new Server instance on localhost port 8080
49 let mut server = Server::<()>::new("localhost", 8080);
50
51 server.route(Method::GET, "/", |req| {
52 // The default log level is Level::Trace so this will be logged
53 trace!("Request from {}", req.address.ip());
54 Response::new()
55 });
56
57 server.start().unwrap();
58 }
59}