1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
/* Copyright 2016 Joshua Gentry * * Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or * http://www.apache.org/licenses/LICENSE-2.0> or the MIT license * <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your * option. This file may not be copied, modified, or distributed * except according to those terms. */ //! This crate allows programs to configure flexi_logger from a configuration file. To do this //! you would first create the configuration file. This can be done dynamically by reading the //! the Cargo.toml. The following code shows creating a log.toml file from the Cargo.toml file: //! //! ``` //! use flexi_config::FlexiConfig; //! //! // Read the Cargo.toml file for the project //! let mut config = FlexiConfig::from_cargo_file("Cargo.toml").unwrap(); //! //! // Change the default directory to "logs" for the log files //! config.disk_dir = Some(String::from("logs")); //! //! // Create a config file named log.toml //! config.to_toml_file("log.toml").unwrap(); //! ``` //! //! Then when your program runs for real, you would load the configuration file and initialize //! flexi_logger with it. The following code is an example of doing that: //! //! ``` //! use flexi_config::{FlexiConfig, Target}; //! //! // Load the log.toml configuration file //! let mut config = FlexiConfig::from_toml_file("log.toml").unwrap(); //! //! // Force the logging to a file instead of stderr (ignoring the config file settings). //! // Then applies the configuration to flexi_logger. //! config.target(Target::Disk).apply(); //! ``` //! //! # Configuration File //! //! If you want to modify the configuration, this can either be done programatically by call //! calling the various methods and accessing the fields of the structure. Or you could hand edit //! the config file. //! //! The configuration file is broken into 3 sections, [common], [disk], and [depends]. //! //! ## [common] //! //! This section handles the general settings for configuring flexi_logger. //! //! ### application //! //! This value shouldn't be changed. This must match the internal name for the application which //! is the "name" property defined in the Cargo.toml file for the application. //! //! ### disk_format & stderr_format //! These settings define the format of the log messages when logging to disk or stderr. There //! are three predefined formats, these formats are actually defined by flexi_logger. //! //! * "default" - This will use the `flexi_logger::default_format` function to format the log message. //! More information can be found //! [here](http://emabee.atwebpages.com/rust/flexi_logger/fn.default_format.html). //! * "detailed" - This will use the `flexi_logger::detailed_format` function to format the log //! message. More information can be found //! [here](http://emabee.atwebpages.com/rust/flexi_logger/fn.detailed_format.html). //! * "opt" - This will use the `flexi_logger::opt_format` function to format the log message. //! More information can be found //! [here](http://emabee.atwebpages.com/rust/flexi_logger/fn.opt_format.html). //! //! In addition you can define a custom format for the log messages. The custom format is defined //! however you want with special control codes inserted between '{' and '}' characters. The //! following codes are supported: //! //! * `f` - Inserts the name of the source file that generated the log message. //! * `p` - Inserts the priority (error, warning, info, debug, trace) as a single lower case //! character. 'e' for error, 'w' for warning, 'i' for info, 'd' for debug, and 't' //! for trace. //! * `P` - Same as `p`, but uses uppercase characters. //! * `pp` - Inserts the priority (error, warning, info, debug, trace) as a 5 character word in //! lower case. 'error' for error, 'warn' for warning, 'info' for info, 'debug' for //! debug, and 'trace' for trace. 'warn' and 'info' will have a space appended so they //! are 5 characters. //! * `PP` - Same as `pp`, but uses uppercase characters. //! * `l` - Inserts the line number of the log message in the source file. //! * `m` - Inserts the module the file belongs to. //! * `c` - Inserts the crate the file belongs to. //! * `t` - Inserts the current time. //! * `e` - Inserts the event or the actual log message. //! //! So a custom format could be like: "{PP} | {c} | {f}:{l} | {e}" which would output the priority //! followed by the crate then the file with line number, and finally the log message. If you want //! to output an curly bracked you would need to escape it with a backslash, like "\\{ {e} \\}". //! //! Additionally when displaying 'f', 'l', 'm', 'c', or 'e' you can specify a width to perform //! left or right justification or truncation. //! //! ```text //! element := '{' type:[[align]width[trim]] '}' //! align := '<' | '>' //! width := integer //! trim := '-' | '' //! ``` //! //! If you want to right justify the filename to 20 characters you would specify "{f:>20}". If //! the filename (with path) is shorter than 20 characters then spaces will be inserted before the //! name until the length is 20 characters. If you want to ensure the length doesn't go over 20 //! characters then you can add the trim. //! //! "{c:>20-}" would output the crate, if the length is less than 20 characters then spaces will //! be prepended, if the length is longer then the last 20 characters of the crate name will be //! displayed. When trim is enabled if the element is right aligned the beginning of the value //! is trimmed, if it is left aligned the end of the string is trimmed. //! //! Trim can also be applied without justifying so you could define: "{e:64-}" which would display //! up 64 characters of the log message then drop any remaining characters. //! //! To output the time, you must specify it should be displayed. Inside the '{' and '}' characters //! you would add a colon (:) followed by the time format, i.e. "{t:<time format>}". The //! time format has it's own special codes: //! //! * `%b` - Inserts the name of the month as 3 characters in lower case, i.e. jan, feb, mar. //! * `%B` - Same as '%b' but uses uppercase characters. //! * `%d` - Inserts the day of the month as two characters, so from 01 to 31. //! * `%f` - Inserts the fractial seconds (milliseconds) as 3 digits, so from 000 to 999. //! * `%H` - Inserts the hour of day in 24 hour format from 00 to 23. //! * `%I` - Inserts the hour of the day in 12 hour format from 01 to 12. //! * `%m` - Inserts the month in numeric format with 2 characters, so from 01 to 12. //! * `%M` - Inserts the minutes in the hour as 2 digits, from 0 to 59. //! * `%p` - Inserts 'am' or 'pm' based on the current time. //! * `%P` - Same as `%p` but uses uppercase characters. //! * `%S` - Inserts the seconds as 2 digits, so from 00 to 59. //! * `%y` - Inserts the last 2 digits of the year, so from 00 to 99. //! * `%Y` - Inserts the full 4 digits of the year. //! * `%%` - Inserts a percent (%) sign. //! //! You would use "{t:%d/%m/%Y %H:%M:%S.%f}" to display the time as //! day/month/year hour:minute/second.milliseconds. //! //! Putting this all together the following format string would basically reproduce flexi_logger's //! detailed format: //! //! ```text //! [{t:%Y-%m-%d %H:%M:%S.%f}] {PP} [{m:32}] {f:32}:{l:>4}: {e} //! ``` //! //! ### priority //! //! This defines the lowest priority message to log. Valid values for this are: //! //! * trace - The lowest level log message. //! * debug - Still low level but not as low as trace. //! * info - Provides informational log messages, higher than trace and debug. //! * warn - Warns of potential issues, this is the second highest log message. //! * error - Highest level priority, reports error situations. //! //! ### Target //! //! Identifies where to log the messages to. This only has two values "stderr" or "disk". //! //! ## [disk] //! //! This section defines some settings that are only used when logging to disk. //! //! ### dir //! //! Identifies a directory to write the log files to. This value can also be false if you want //! the files to be created in the current directory. //! //! ### dup_err //! //! Flexi_logger can duplicate any "error" messages to both disk and stdout. If you like the //! "error" log messages also written to stdout, set this to "true". //! //! ### dup_info //! //! Flexi_logger can duplicate any "info" messages to both disk and stdout. If you like the "info" //! log messages also written to stdout, set this to "true". //! //! ### extension //! //! Provides the extension for the log files that are created. By default this is "log" but can //! be changed to suit your needs. //! //! ### max_size //! //! The default for this is "false" to indicate don't limit the log file sizes, just create a new //! file each day. If this is set, it specifies the number of megabytes the file can grow to //! before a new file should be created. //! //! ### name_suffix //! //! The default for this is "false". If you would like to add a custom suffix to the file name it //! can be specified with this parameter. This maps to the discriminant field of flexi_logger's //! [LogConfig](http://emabee.atwebpages.com/rust/flexi_logger/struct.LogConfig.html) structure. //! //! ### timestamp //! //! This value controls if the timestamp is added to the file name when the file is created. //! //! ## [depends] //! //! This section defines the log priorities for any dependant crates for your application. If //! your application depends both on the "rand" and "time" crates, you could add: //! //! ```text //! [depends] //! rand = "warn" //! time = "trace" //! ``` //! //! To enable warning messages and higher from "rand" and enable all log messages from "time". //! The priorities are defined the same way as in the [common] section, so you have: //! //! * trace - The lowest level log message. //! * debug - Still low level but not as low as trace. //! * info - Provides informational information, higher than trace and debug. //! * warn - Warns of potential issues, this is the second highest log message. //! * error - Highest level priority, reports error situations. extern crate flexi_logger; #[macro_use] extern crate lazy_static; extern crate log; extern crate time; extern crate toml; #[cfg(test)] extern crate rand; mod appender; mod config; mod flexi_config_cargo; mod flexi_config_from_toml; mod flexi_config_to_toml; mod flexi_config_setters; use std::fmt::Write; use std::collections::BTreeMap; pub use config::{Issues, LogFormat, Priority, Target}; use flexi_logger::LogConfig; //************************************************************************************************* /// Main structure for the crate. This object is used to create the configuration file, load the /// configuration file, and apply the settings to flexi_logger. /// /// This object will initialize flexi_logger to start logging messages. It can be created /// programatically, from a Cargo.toml file, or from a configuration TOML file. Once the settings /// are correct the configuration can be applied to flexi_logger and logging can start. #[derive(Debug, Clone)] pub struct FlexiConfig { //--------------------------------------------------------------------------------------------- /// Defines the name of the application. pub project : String, //--------------------------------------------------------------------------------------------- /// Defines the list of modules the application depends on and the lowest level log message // to actually log. pub dependencies : BTreeMap<String, Option<Priority>>, //--------------------------------------------------------------------------------------------- /// Defines where the log messages should be written to, disk or stderr? By default this is /// set to stderr. pub target : Target, //--------------------------------------------------------------------------------------------- /// Defines the log format when writing to stderr. By default this will use the flexi_logger /// default format. pub stderr_format : LogFormat, //--------------------------------------------------------------------------------------------- /// Defines the log format when writing to disk. By default this will use the flexi_logger /// detailed format. pub disk_format : LogFormat, //--------------------------------------------------------------------------------------------- /// If logging to disk is enabled, this sets the directory to write to. By default (None) /// it will write to the current directory. pub disk_dir : Option<String>, //--------------------------------------------------------------------------------------------- /// When logging to disk, flexi_logger can duplicate any error messages to stdout. The /// default is to duplicate the error messages. pub disk_dup_err : bool, //--------------------------------------------------------------------------------------------- /// When logging to disk, flexi_logger can duplicate any info messages to stdout. The /// default is to not duplicate the messages. pub disk_dup_info : bool, //--------------------------------------------------------------------------------------------- /// The extension for the log file. By default this is "log". pub disk_filename_ext : String, //--------------------------------------------------------------------------------------------- /// Flag to tell flexi_logger to include the timestamp when a log file is created. This is set /// to true by default. If the file_limit_size is set however this value will be ignored. pub disk_filename_time : bool, //--------------------------------------------------------------------------------------------- /// If set, limits the size of the log file in megabytes. When this size is reached a new /// file is created. If this value is set the log files will have a sequence number rather /// than a time stamp. pub disk_file_size : Option<u32>, //--------------------------------------------------------------------------------------------- /// Adds a suffix to the log file names This will be included after the program name but // before the timestamp. pub disk_filename_suffix : Option<String>, //--------------------------------------------------------------------------------------------- /// Sets the lowest priority to report for you application. The default priority is Warn. pub app_priority : Priority, //--------------------------------------------------------------------------------------------- /// If the object was loaded from a TOML configuration file, this object will contain any /// issues encountered while loading the file. pub issues : Option<Issues> } impl FlexiConfig { //********************************************************************************************* /// Creates an instance of the object from the values passed in. /// /// This could be used to create a configuration programatically. /// /// # Examples /// /// Create an initial configuration file that can be modified by a human. /// /// ``` /// use std::collections::BTreeMap; /// use flexi_config::{FlexiConfig, Priority}; /// /// let mut depends = BTreeMap::new(); /// /// depends.insert(String::from("time"), None); /// depends.insert(String::from("rand"), Some(Priority::Debug)); /// /// let config = FlexiConfig::new("foo", depends); /// /// config.to_toml_file("log.toml"); /// ``` /// /// Create a configuration and apply it to flexi_config immediately. /// /// ``` /// use std::collections::BTreeMap; /// use flexi_config::{FlexiConfig, Priority}; /// /// let mut depends = BTreeMap::new(); /// /// depends.insert(String::from("time"), Some(Priority::Warn)); /// depends.insert(String::from("rand"), Some(Priority::Debug)); /// /// let config = FlexiConfig::new("foo", depends); /// /// config.apply().unwrap(); /// ``` /// pub fn new( project : &str, dependencies : BTreeMap<String, Option<Priority>> ) -> FlexiConfig { FlexiConfig { project : String::from(project), dependencies : dependencies, target : Target::StdErr, stderr_format : LogFormat::Default, disk_format : LogFormat::Detailed, disk_dir : None, disk_dup_err : true, disk_dup_info : false, disk_filename_ext : String::from("log"), disk_filename_time : true, disk_file_size : None, disk_filename_suffix : None, app_priority : Priority::Warn, issues : None } } //********************************************************************************************* /// Applies the configuration to flexi_logger. /// /// Any log messages generated before this call will be lost. This method should only ever be /// called once, the logger configuration cannot change after it is set. /// /// # Examples /// /// Apply a programatic configuration that doesn't allow the user to change anything. /// /// ``` /// use std::collections::BTreeMap; /// use flexi_config::{FlexiConfig, Priority}; /// /// let mut depends = BTreeMap::new(); /// /// depends.insert(String::from("time"), Some(Priority::Warn)); /// depends.insert(String::from("rand"), Some(Priority::Debug)); /// /// let config = FlexiConfig::new("foo", depends); /// /// config.apply().unwrap(); /// ``` /// /// Load a configuration file from disk and apply it. /// /// ``` /// use flexi_config::FlexiConfig; /// /// let config = FlexiConfig::from_toml_file("log.toml").unwrap(); /// /// config.apply().unwrap(); /// ``` pub fn apply(self) -> Result<(), String> { //----------------------------------------------------------------------------------------- // Create the flexi_logger configuration. let mut config = LogConfig::new(); match self.target { Target::StdErr => { config.format = try!(self.stderr_format.format_function()); config.log_to_file = false; config.print_message = false; }, Target::Disk => { config.format = try!(self.disk_format.format_function()); config.log_to_file = true; config.print_message = false; config.duplicate_error = self.disk_dup_err; config.duplicate_info = self.disk_dup_info; config.directory = self.disk_dir; config.suffix = Some(self.disk_filename_ext); config.timestamp = self.disk_filename_time; config.rotate_over_size = self.disk_file_size.map(|x| x as usize * 1024 * 1024); config.discriminant = self.disk_filename_suffix; } } //----------------------------------------------------------------------------------------- // Create the logging spec. let mut spec = String::with_capacity(1024); write!(spec, "{}={}", self.project, self.app_priority.encode()).unwrap(); for (depends, priority) in self.dependencies.iter() { if let Some(priority) = priority.as_ref() { write!(spec, ",{}={}", depends, priority.clone().encode()).unwrap(); } } //----------------------------------------------------------------------------------------- // Initialize flexi_logger match flexi_logger::init(config, Some(spec)) { Ok(_) => Ok(()), Err(msg) => Err(format!("{}", msg)) } } } #[cfg(test)] mod tests { use FlexiConfig; //********************************************************************************************* /// Test creating/saving/loading a configuration. #[test] fn test() { let config = FlexiConfig::from_cargo(" [package] name = \"test\" [dependencies] one = \"*\" two = \"*\" three = \"*\" ").unwrap(); let save = config.to_toml_string(); let copy = FlexiConfig::from_toml_string(&save).unwrap(); assert!(copy.issues.is_none()); } }