Giter Club home page Giter Club logo

Comments (4)

dpc avatar dpc commented on August 29, 2024 2

You form your Drain somewhere at the start of your app, depending on your app requirements (do you want to log to text file, console, both? In which formats, at which level). Only the binary (app) author can know the exact requirements how to handle logging, so that's why it happens there first.

From that drain you build your root logger with Logger::root.

Then you pass Logger objects around. You can clone them, you can also build more information in child-Loggers by using Logger::new. Anything that needs to log: libraries, modules, structs itself, should generally accept a Logger during initialization and store it somewhere.

In Iron most probably you want to create one Loggerfor the instance of your server (with information like build version, host, port it is listening on). Then at the beginning of your middleware chain, create a child Logger with per-request infor like: peer address, peer port, url requested etc. Put that child Logger into iron::request::Request::extensions or somewhere else that is being preserved between parts of middleware. (I'm not sure of the details here, you might want to ask Iron devs what is the best place. extensions look to me like it will do).

And that's pretty much it. If you use some libraries that do not use slog and you'd want them to be logged withing slog you might needs to look into slog_stdlog create documentation and examples/ dir of slog ("oldlogging" is the keyword).

In case of troubles please ping me on gitter. I really appreciate feedback and I'm interested in all things good and bad about using slog.

from slog.

iamsebastian avatar iamsebastian commented on August 29, 2024 2

Just if someone is searching:

main.rs

fn main() {
    let log = Logger::root(slog_term::streamer().full().build().fuse(),
                           o!("version" => env!("CARGO_PKG_VERSION")));
    let mut srv = Nickel::new();
    srv.utilize(middlewares::LoggingMiddleware::new(log.clone()));
}

middlewares::LoggingMiddleware

use nickel::{Middleware, MiddlewareResult, Request, Response};
use nickel_jwt_session::SessionRequestExtensions;
use slog::Logger;

pub struct LoggingMiddleware {
    log: Logger
}

impl LoggingMiddleware {
    pub fn new(log: Logger) -> LoggingMiddleware {
        LoggingMiddleware {
            log: log,
        }
    }
}

/// Just log some information about restricted access of authorized users.
impl<D> Middleware<D> for LoggingMiddleware {
    fn invoke<'mw, 'conn>(&self, req: &mut Request<'mw, 'conn, D>, mut res: Response<'mw, D>) -> MiddlewareResult<'mw, D> {
        use helpers::request::RequestLogExtension;

        let mut log = self.log.clone();
        let mut path = String::new();

        if let Some(users_mail) = req.authorized_user() {
            log = log.new(o!("user" => users_mail.clone()));
        }

        if let Some(pth) = req.path_without_query() {
            path = pth.to_owned().clone();
        }

        log = log.new(o!("path" => path));

        info!(log, "access");

        // custom Trait, where logger gets set -- see below
        req.set_logger(log);

        res.next_middleware()
    }
}

helpers::request::RequestLogExtension

pub struct Loggr;

impl Key for Loggr { type Value = Logger; }

pub trait RequestLogExtension {
    fn get_logger(&self) -> Logger;
    /// Set the logger drain
    fn set_logger(&mut self, log: Logger);
}

impl<'a, 'b, D> RequestLogExtension for Request<'a, 'b, D> {
    fn get_logger(&self) -> Logger {
        use plugin::Extensible;
        self.extensions().get::<Loggr>().unwrap().clone()
    }

    fn set_logger(&mut self, log: Logger) {
        use plugin::Extensible;
        self.extensions_mut().insert::<Loggr>(log);
    }
}

from slog.

dpc avatar dpc commented on August 29, 2024 1

Oh. You are using nickel, not Iron. With quick look at Nickel I see that there's some support for logging logic in nickel, so it might be worth asking Nickel devs how to do it best (maybe slog-nickel/nickel-slog crate should be created to make it nice&easy). But it looks that:

http://docs.nickel.rs/nickel/struct.Request.html

extensions is the place where you can put your own stuff, so slog::Logger should fit there just fine.

from slog.

iamsebastian avatar iamsebastian commented on August 29, 2024

Thanks so much, for your great feedback.

It's not painless, to understand these concepts of extending existent stuff in rust, when you only became a script-kiddie script-language guy after ten years of work with: js, bash/zsh (some ruby, py, etc.)

I will report back, if I implemented something. Till then, I close this issue, since it's blowing up the issues in this project.

Thanks again.

from slog.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.