evgenyigumnov / cblt

Safe and fast minimalistic web server, written in Rust, that serves files from a directory and proxies requests to another server.
MIT License
39 stars 7 forks source link

Logging improvement #28

Open evgenyigumnov opened 4 days ago

evgenyigumnov commented 4 days ago
  1. remove env_logger
  2. use trace
    
    use tracing::info;
    use tracing_subscriber::fmt::writer::BoxMakeWriter;
    use tracing_subscriber::{fmt, layer::SubscriberExt, util::SubscriberInitExt};

fn main() { let file_appender = tracing_appender::rolling::daily("/var/log/my_server", "server.log"); let (non_blocking, _guard) = tracing_appender::non_blocking(file_appender);

tracing_subscriber::registry()
    .with(fmt::layer().with_writer(non_blocking))
    .init();

info!("Server started!!!");
error!("Error!!!");

}

3. add "log" directive and use in "log_request_response" funcion

"example.com" { log { output file "/var/log/caddy/example.com.access.log" } ... }

if directive absend do not write accesslog

```rust
use tracing::{info, Level};
use tracing_subscriber::{fmt, layer::SubscriberExt, util::SubscriberInitExt};
use tracing_appender::non_blocking::WorkerGuard;

fn main() {
    // Create file appenders for different logs
    let service1_file = tracing_appender::rolling::daily("/var/log/my_server", "service1_info.log");
    let service2_file = tracing_appender::rolling::daily("/var/log/my_server", "service2_info.log");

    // Make them asynchronous
    let (service1_writer, _service1_guard): (_, WorkerGuard) = tracing_appender::non_blocking(service1_file);
    let (service2_writer, _service2_guard): (_, WorkerGuard) = tracing_appender::non_blocking(service2_file);

    // Create logging layers for different services
    let service1_layer = fmt::layer()
        .with_writer(service1_writer)
        .with_filter(Level::INFO);

    let service2_layer = fmt::layer()
        .with_writer(service2_writer)
        .with_filter(Level::INFO);

    // Initialize `tracing` with both layers
    tracing_subscriber::registry()
        .with(service1_layer)
        .with(service2_layer)
        .init();

    // Example logs for different services
    log_service1();
    log_service2();
}

fn log_service1() {
    info!(target: "service1", "This is an INFO message for service 1");
}

fn log_service2() {
    info!(target: "service2", "This is an INFO message for service 2");
}
  1. add error log by parameter --error-log=/path/error.log if absent do not log errors