Skip to main content

basic/
logging.rs

1use afire::{
2    extension::logger::{Level, Logger},
3    Content, HeaderType, Method, Middleware, Response, Server,
4};
5
6use crate::Example;
7
8// You can run this example with `cargo run --example basic -- logging`
9
10// Use some of afire's built-in middleware to log requests.
11
12pub struct Logging;
13
14impl Example for Logging {
15    fn name(&self) -> &'static str {
16        "logging"
17    }
18
19    fn exec(&self) {
20        // Create a new Server instance on localhost port 8080
21        let mut server = Server::<()>::new("localhost", 8080);
22
23        // Define a handler for GET "/"
24        server.route(Method::GET, "/", |_req| {
25            Response::new()
26                .text("Hello World!\nThis request has been logged!")
27                .content(Content::TXT)
28        });
29
30        // Make a logger and attach it to the server
31
32        // By default Log Level is INFO, File is None and Console is true
33        // This could be condensed to `Logger::new().attach(&mut server);` as it uses al default values
34        Logger::new()
35            // The level of logging this can be Debug or Info
36            // Debug will give a lot more information about the request
37            .level(Level::Info)
38            // This will have Logger make use of the RealIp extention,
39            // which will allow logging the correct IP when using a reverse proxy.
40            .real_ip(HeaderType::XForwardedFor)
41            // The file argument tells the logger if it should save to a file
42            // Only one file can be defined per logger
43            // With logging to file it will write to the file on every request... (for now)
44            .file("example.log")
45            .unwrap()
46            // Tells the Logger it should log to the console as well
47            .console(true)
48            // This must be put at the end of your Logger Construction
49            // It adds the Logger to your Server as Middleware
50            .attach(&mut server);
51
52        // Now if you goto http://localhost:8080/ you should see the log message in console.
53
54        // Start the server
55        // This will block the current thread
56        server.start().unwrap();
57    }
58}