Log4j-one of the "weapons" required by the system

Source: Internet
Author: User

 
Introduction
Log4j is an open-source project of Apache. By using log4j, we can control the log information delivery destination, such as the console, file, database, and even the interface server; you can also control the output format of each log. By defining the level of each log information, you can control the log generation process in greater detail.
When necessary, you can use a configuration file to flexibly configure the program without modifying the program code.
 
Install
  • Slave
  • Decompress the archive file to a suitable directory.
  • Add the file Dist/lib/log4j-1.2.11.jar to the classpath environment variable
  •  
    Our concerns
    For a log processing function, we have three main concerns:
    Who will record logs? -- Logger
  • How to obtain a logger instance?
  • 1. There are many ways to create a logger. The following method can retrieve the root logger:
    Logger logger = logger. getrootlogger ();
    2. Create a New logger as follows:
    Logger logger = logger. getlogger ("logtest ");
    3. A common usage is to instantiate a static global Logger Based on the class name:
    Static logger = logger. getlogger (logtest. Class );
  • How to record logs?
  • Log Level) Corresponding logging method (logger)
    Fatal (0) Log. Fatal ()
    Error (3) Log. Error ()
    Warn (4) Log. Warn ()
    Warn (6) Log.info ()
    Debug (7) Log. debug ()
    Where is the record? -- Appender
    1. eagleappender uses the layout (layout) specified by the user to output log events to system. out or system. Err. The default target is system. Out.
    2. dailyrollingfileappender extends fileappender. Therefore, multiple log files can be recorded cyclically at a frequency selected by one user.
    3. fileappender writes log events to a file
    4. rollingfileappender extends the fileappender backup capacity to a certain size of log files.
    5. writerappender writes log events to writer or outputstream based on the user's choice.
    6. jdbcappender writes log events to the database.
    Log format? -- Logger
    1. HTML layout formatted log output is an HTML table.
    2. patternlayout format the log output based on the specified conversion mode, or use the default conversion mode if no conversion mode is specified.
    3. simplelayout format the log output in a very simple way. It prints the level, and then follows a break "-". Finally, it is the log message.
    Configuration File description
    The ease-of-use of log4j is its configurability. By specifying problems 2 and 3 in the configuration file above, our system has a powerful and almost perfect logging function! The following is an example of a configuration file: logconfig. Properties

    Log4j. rootlogger = debug, console, A1, Im
    Log4j.addivity.org. Apache = true

    # Apply to the console
    Log4j. appender. Console = org. Apache. log4j. leleappender
    Log4j. appender. Threshold = debug
    Log4j. appender. Console. Target = system. Out
    Log4j. appender. Console. layout = org. Apache. log4j. patternlayout
    Log4j. appender. Console. layout. conversionpattern = [framework] % d-% C-%-4r [% T] %-5 p % C % x-% m % N
    # Log4j. appender. console. layout. conversionpattern = [start] % d {date} [date] % N % P [Priority] % N % x [NDC] % N % T [thread] n % C [category] % N % m [Message] % N

    # Apply to files
    Log4j. appender. File = org. Apache. log4j. fileappender
    Log4j. appender. file. File = file. Log
    Log4j. appender. file. append = false
    Log4j. appender. file. layout = org. Apache. log4j. patternlayout
    Log4j. appender. file. layout. conversionpattern = [framework] % d-% C-%-4r [% T] %-5 p % C % x-% m % N

    # Used to generate files by day
    Log4j. appender. A1 = org. Apache. log4j. dailyrollingfileappender
    Log4j. appender. a1.file = samplemessages. log4j
    Log4j. appender. a1.datepattern = yyyymmdd-hh '. log4j'
    Log4j. appender. a1.layout = org. Apache. log4j. xml. xmllayout

    # Apply to file rollback
    Log4j. appender. rolling_file = org. Apache. log4j. rollingfileappender
    Log4j. appender. rolling_file.threshold = Error
    Log4j. appender. rolling_file.file = rolling. Log
    Log4j. appender. rolling_file.append = true
    Log4j. appender. rolling_file.maxfilesize = 10kb
    Log4j. appender. rolling_file.maxbackupindex = 1
    Log4j. appender. rolling_file.layout = org. Apache. log4j. patternlayout
    Log4j. appender. rolling_file.layout.conversionpattern = [framework] % d-% C-%-4r [% T] %-5 p % C % x-% m % N

    # For Databases
    # Description: Database: MySQL
    # First create a database table (log4j) Description:
    # Field description
    # Guid serial number (auto-increment column)
    # Date time
    # Current thread
    # Level current level
    # Class current Java program/Method
    # Current message output
    Log4j. appender. Database = org. Apache. log4j. JDBC. jdbcappender
    Log4j. appender. database. url = JDBC: mysql: // localhost: 3306/test? Useunicode = true & characterencoding = GBK
    Log4j. appender. database. Driver = com. MySQL. JDBC. Driver
    Log4j. appender. database. User = root
    Log4j. appender. database. Password =
    Log4j. appender. database. SQL = insert into log4j (date, thread, level, class, message) values ('% d {yyyy-mm-dd hh: mm: SS}', '% t ', '% P',' % l', '% m ')
    Log4j. appender. database. layout = org. Apache. log4j. patternlayout
    Log4j. appender. database. layout. conversionpattern = [framework] % d-% C-%-4r [% T] %-5 p % C % x-% m % N

    # Custom appender
    Log4j. appender. Im = net. cybercorlin. util. Logger. appender. imappender
    Log4j. appender. Im. Host = mail.cybercorlin.net
    Log4j. appender. Im. Username = Username
    Log4j. appender. Im. Password = Password
    Log4j. appender. Im. Recipient = corlin@cybercorlin.net
    Log4j. appender. Im. layout = org. Apache. log4j. patternlayout
    Log4j. appender. Im. layout. conversionpattern = [framework] % d-% C-%-4r [% T] %-5 p % C % x-% m % N

    # Meaning of "% d % T % P % L % m % N:

    # % D date or time of the log output time point. The default format is iso8601. You can also specify the format after it, for example, % d {yyyy-mm-dd hh: mm: SS}, output is similar to: 17:49:27;
    # % T name of the thread that generates the log event;
    # % P the log_level of the log, such as debug, warn, Or info;
    # % C output category, usually the full name of the class, such as "iNotes. Default ";
    # % M log content;
    # % L location of log event output, including category name, thread, and number of lines in the code. For example, write2database. Main (write2database. Java: 33 );
    # % N output a carriage return line break, which is "" on Windows and "" On Unix

     
    Example

    Package com. javer. Test. log4j;

    Import org. Apache. log4j. Logger;
    Import org. Apache. log4j. propertyconfigurator;
    Import org. Apache. log4j. htmllayout;

    /**
    * Javer's log4j example Program
    * @ Author javer QQ: 84831612
    * @ Version 1.0
    * @ Version http://blog.csdn.net/java008
    */
    Public class logtest
    {
    Public static void main (string [] ARGs)
    {
    String filepath = "F: // logconfig. properties ";
    Propertyconfigurator. Configure (filepath );
    Logger log = logger. getlogger (logtest. Class );
    // Log. addappender (New htmllayout ());
    For (INT I = 0; I <10; I ++)
    {
    Log.info ("section" + (I + 1) + "debugging information ");
    Log. debug ("sqlexception:", new java. SQL. sqlexception ("SQL exception! "));
    Log.info ("Hello log4j! ");
    }
    }
    }

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.