Basic concepts in log4rs

0 17
Logs are an important part of the application. Whether it is a server-side progr...

Logs are an important part of the application. Whether it is a server-side program or a client-side program, logs are needed as error output or business records. In this article, we combinelog4rsLet's talk about how to use logs in rust programs.
log4rsSimilar to log4j in the Java ecosystem, the usage is also very similar

Basic concepts in log4rs

The functional components of log4rs are also composed of appenders and loggers.

  • Basic concepts in log4rs

    appender
    Responsible for appending logs to the specified file or console

  • logger
    Contains multiple appenders, for example, if a log needs to be output to the console and also persisted to a log file, you can bind ConsoleAppender and FileAppender at the same time in the logger

log4rs usage example

  • Example description
    We need to record system logs and business logs in the project, respectively recorded in logs/sys.log and logs/business.log

  • Define appender and logger and initialize
    The code location is src/logger/logger.rs

    let sys_file = FileAppender::builder()
          .encoder(Box::new(PatternEncoder::new("{d} - {m}{n}")))
          .build("logs/sys.log")
          .unwrap();
      let business_file = FileAppender::builder()
          .encoder(Box::new(PatternEncoder::new("{d} - {m}{n}")))
          .build("logs/business.log")
          .unwrap();
    
      let stdout = ConsoleAppender::builder().build();
    
      let config = Config::builder()
          .appender(Appender::builder().build("stdout", Box::new(stdout)))
          .appender(Appender::builder().build("sys", Box::new(sys_file)))
          .appender(Appender::builder().build("business", Box::new(business_file)))
          .logger(
              Logger::builder()
                  .appender("sys")
                  .build("syslog", LevelFilter::Info),
          )
          .logger(
              Logger::builder()
                  .appender("business")
                  .build("businesslog", LevelFilter::Info),
          )
          .build(
              Root::builder()
                  .appender("stdout")
                  .appender("file_out")
                  .build(LevelFilter::Info),
          )
          .unwrap();
    
      let _ = log4rs::init_config(config).unwrap();
    

    The code defines two FileAppender instances, sys_file and business_file, which are used to append logs to files like sys.log and business.log.
    The config defines two loggers, respectively bound to sys appender and business appender.
    Finally, initialize log4rs through init_config.

    • Output logs in the program

      • Define the uselog command and two subcommands, respectively inputting sys log and business log.
        Code location: src/cmd/cmdusedifflogger.rs

        pub fn new_use_log_cmd() -> Command<'static> {
            clap::Command::new("uselog")
                .about("use diffrent target log")
                .subcommand(new_use_sys_log_cmd())
                .subcommand(new_use_business_log_cmd())
        }
        
        pub fn new_use_sys_log_cmd() -> Command<'static> {
            clap::Command::new("syslog").about("append to syslog")
        }
        
        pub fn new_use_business_log_cmd() -> Command<'static> {
            clap::Command::new("businesslog").about("append to business log")
        }
        
      • Parse commands and output logs
        Code location: src/cmd/rootcmd.rs

        if let Some(ref log) = matches.subcommand_matches("uselog") {
            println!("use log");
            if let Some(_) = log.subcommand_matches("syslog") {
                log::info!(target:"syslog","Input sys log");
            }  
            if let Some(_) = log.subcommand_matches("businesslog") {
                log::info!(target:"businesslog","Input business log");
            }
        }
        

        When outputting, distinguish the output to different loggers through target.

The GitHub address of this code is: https://github.com/jiashiwen/interactcli-rs

To be continued

Author: JD Technology Jia Shiwén

Source: JD Cloud Developer Community. Please indicate the source of the reprint.

你可能想看:

Article 2 of the Cryptography Law clearly defines the term 'cryptography', which does not include commonly known terms such as 'bank card password', 'login password', as well as facial recognition, fi

d) Adopt identification technologies such as passwords, password technologies, biometric technologies, and combinations of two or more to identify users, and at least one identification technology sho

It is possible to perform credible verification on the system boot program, system program, important configuration parameters, and application programs of computing devices based on a credible root,

b) It should have a login failure handling function, and should configure and enable measures such as ending the session, limiting the number of illegal login attempts, and automatically logging out w

As announced today, Glupteba is a multi-component botnet targeting Windows computers. Google has taken action to disrupt the operation of Glupteba, and we believe this action will have a significant i

4.5 Main person in charge reviews the simulation results, sorts out the separated simulation issues, and allows the red and blue teams to improve as soon as possible. The main issues are as follows

5. Collect exercise results The main person in charge reviews the exercise results, sorts out the separated exercise issues, and allows the red and blue sides to improve as soon as possible. The main

b) It should have the login failure handling function, and should configure and enable measures such as ending the session, limiting the number of illegal logins, and automatically exiting when the lo

Announcement regarding the addition of 7 units as technical support units for the Ministry of Industry and Information Technology's mobile Internet APP product security vulnerability database

In today's rapidly developing digital economy, data has become an important engine driving social progress and enterprise development. From being initially regarded as part of intangible assets to now

最后修改时间:
admin
上一篇 2025年03月27日 12:17
下一篇 2025年03月27日 12:39

评论已关闭