#logging #slog #unwrap #panic #log


Syntactic sugar to slog an error before unwrapping

6 releases

0.1.5 Mar 10, 2019
0.1.4 Mar 9, 2019

#282 in Debugging


70 lines

slog_unwraps Build Status docs code size Build Status Project Status: Active – The project has reached a stable, usable state and is being actively developed.

Syntactic sugar to slog an error before unwrapping. It will add caller file and line information to the log statement so you don't have to turn on RUST_BACKTRACE to see what went wrong, but know that that only makes sense in debug mode. In release mode this information will either be missing or unreliable.

At first I had an expects function as well to be able to add context, but I really think you should use the failure crate, which provides a context method on errors, and it's much cleaner, so expects no longer exists. If you don't want to use failure, you will have to make sure your errors display sensible messages.


run with cargo run --example basic

   std          :: { fs::File                       } ,
   slog         :: { Drain, Level, Logger, o, crit  } ,
   slog_term    :: { FullFormat, PlainSyncDecorator } ,
   slog_unwraps :: { ResultExt                      } ,

fn main()
   let plain = PlainSyncDecorator::new( std::io::stderr() )                  ;
   let log   = Logger::root( FullFormat::new( plain ).build().fuse(), o!() ) ;

   // This will output (in one line, wrapped here for readablility):
   // Mar 08 18:13:52.034 CRIT PANIC - fn `main` calls `unwraps` @ examples/basic.rs:20
   // -> Error: No such file or directory (os error 2)
   // and then will call unwrap for you
   let f     = File::open( "dont.exist" );
   let _file = f.unwraps( &log );

   // This is equivalent. Of course you can do something else with the result after logging
   // rather than unwrapping. This only logs if the result is an error.
   let g     = File::open( "dont.exist" );
   let _file = g.log( &log, Level::Critical ).unwrap();

   // Without this crate, everytime you want to unwrap, you would write something like:
   let h     = File::open( "dont.exist" );

   let _file = match h
      Ok ( f ) => f,
      Err( e ) => { crit!( log, "{}", e ); panic!() }

License: Unlicense


~116K SLoC