Application log4cxx logs in c ++

Source: Internet
Author: User
1. IntroductionLog4cxx is a sub-project of Apache Logging Service, an open-source project. It is a c ++ porting version of log4j, a well-known Java Community, used to provide log functions for C ++ programs, this allows developers to debug and audit the target program. More information about log4cxx can be obtained from the website http://logging.apache.org of the Apache Loggin Service. The current stable version is 0.9.7. The content of this article and the sample code are based on this version.

2.1 obtain the Software PackageObtain the appropriate version from the official website. You can also directly obtain the link from the following link (the direct link address may not always be valid): http://logging.apache.org/after the download is complete, decompress it to the appropriate directory.

2.2 compileThe original release package does not contain compiled code. We need to do this by ourselves. Open your IDE and open log4cxx. dsw loads the project in the following directory: l Msvc/static: This project generates the static Link Library of log4cxx (lib4cxx. lib and lib4cxxs. lib); l Msvc/dll: This project generates the dynamic link library (lib4cxx. dll ). Normally, the project can be compiled successfully. View the output directory and find the generated library files for use in the next step. 2.3 set the project environmentOpen a project in the IDE that requires adding the log function, or create a project for the purpose of experiment to set it. First, set the include file for log4cxx. These files are located in the include/log4cxx directory of the log4cxx software package. Check the content listed in "Tools> Options> Project> VC ++ directory> include files" in your VC ++ IDE, to determine how you add these include files: l directly copies include/log4cxx to the defined include file directory. If you regard log4cxx as a system service, this is reasonable because you can use it as a standard library, for example: # include <log4cxx/logger. h> l add an inclusion path to point to a file directory located outside the IDE. You can simply point to the log4cxx package directory created after decompression in 2.1. Next, you need to set the log4cxx library generated in section 2.2. It depends on how you use the database: static or dynamic link. L in the case of static links, you need to do the following: Define the log4cxx_static macro for the pre-compiler, set the location to "Project-> setting-> C/C ++-> categroy-> preprossor-> proprossor definitions", and specify the dependent library lib4cxxs for the linker. when lib and ws2_32.libl are dynamically linked, you only need to specify the dependent library lib4cxxs for the linker. lib. The setting method is the same as above.

3. Sample CodeThis section describes the simplest log4cxx example so that you can quickly understand it. In this example, a log service is created. The log can be controlled through the configuration file and output information to the file and the console at the same time. In terms of implementation, we adopt a simple console program and use log4cxx using dynamic link libraries. To achieve this goal, follow these steps: 1) create a blank win32 console project named logdemo and set it according to the content described in section 2.3. Note: here we use the dynamic connection interface. 2) Add the code to implement the log function in logdemo. cpp. The code list after completion is as follows:

# Include "stdafx. h"
# Include <log4cxx/logger. h>
# Include <log4cxx/propertyconfigurator. h>
 
Using namespace log4cxx;
 
Int _ tmain (int argc, _ TCHAR * argv [])
{
// Load the log4cxx configuration file. The attribute file is used here.
PropertyConfigurator: configure ("log4cxx. properties ");

// Obtain a Logger. The RootLogger is used here.
LoggerPtr rootLogger = Logger: getRootLogger ();

// Send an output request at the info level
Log4cxx_info (rootlogger, _ T ("it does work "));
// Rootlogger-> Info (_ T ("it does work"); // similar to the above sentence
 
Return 0;
}

Because we need to use software packages in the next step, including compiling and copying necessary files.

Compile the project in Debug mode and Debug the program until it is successful.

3) create a text file named log4cxx. properties, and enter the following content: # Set the root logger to the debug level, using the CA and FA appender
Log4j. rootlogger = debug, CA, Fa
 
# Set appender FA:
# This is a file-type appender,
# Its output file (File) is./output. log,
# The output mode (append) is the overwrite mode,
# The output format (layout) is patternlayout.
Log4j. appender. Fa = org. Apache. log4j. fileappender
Log4j. appender. Fa. File =./output. Log
Log4j. appender. Fa. append = true
Log4j. appender. Fa. layout = org. Apache. log4j. patternlayout
Log4j. appender. fa. layout. ConversionPattern = % d [% t] %-5 p %. 16c-% m % n
 
# Set the Appender ca:
# This is a console-type Appender.
# The output format (layout) is PatternLayout.
Log4j. appender. ca = org. apache. log4j. leleappender
Log4j. appender. ca. layout = org. apache. log4j. PatternLayout
Log4j. appender. ca. layout. ConversionPattern = % d [% t] %-5 p %. 16c-% m % n4) Copy log4cxx. dll to the output directory. In the dynamic connection mode, the application needs to be able to find the library file. 5. Run the generated logdemo.exe file and check the running result to see if our work has been successful. If everything goes smoothly, you should be able to see the output content similar to the following in both the console and the output file:

16:09:50, 609 [2528] INFO root-it does work

 

4. Architecture 4.1 core categoriesLog4cxx has three key components: loggers, appenders, and layouts. Logger is the core class of log4cxx. You only need to perform log operations. looger has a hierarchical structure with the top-level RootLogger. logger has a level. Each logger can append multiple Appender. Appender indicates the log output target, such as output to a file or console. You can use layout to set the format of each appender. These three types of components are represented as follows (not class relationships): (TODO: describes the three components here) 4.2 configuration classIn addition, the classes used include BasicConfigurator, PropertyConfigurator, and DOMConfigurator, which are used to configure log4cxx. The BasicConfigurator provides a simple configuration, including using ConsoleAppder as the root appender and PatternLayout as the default layout. PropertyConfigurator uses the properties file as the configuration method. DOMConfigurator uses the properties file as the configuration method. (TODO: Describe the configuration content here) 5. Practical GuidanceWhether to use logs in projects and how to use logs is a technical choice that developers need to make. This usually involves system performance and log usage. The way we use logs, some of which have accumulated many years of experience in this industry, some of which are purely personal preferences. 1) when to use logs normally, logs are used for debugging and auditing. If your project has special requirements for this, you can consider using logs. Debugging is usually used in areas where the IDE debugger cannot reach. Common scenarios include debugging distributed components. On the server side, you need to call the client to verify whether the operation is correct. At this time, the log output is used as a auxiliary tool to diagnose the error. Link Library debugging. This method is very effective when it cannot be tracked into an external database. Debugging in the production environment. The production environment usually refers to the formal operation of the product at the customer's place. When a problem occurs, the developer is often absent from the site. It is a very effective way to identify the error with the help of the log output. For audit applications, it depends on the specific situation. The program-level record capability can undoubtedly be effectively supplemented as a business-level audit measure. Log4cxx can be competent in any scenario, depending on its flexible configuration capabilities and various types of output methods. 2) Disable logs due to performance issues. You can use the configuration file to disable or enable logs and use macros to output logs instead of logger output commands. Create a logger hierarchy and select the output target based on the level. Minimize the number of output targets and select an appropriate output format. Using SimpleLayout will achieve the same speed as std: cout. 3) All qualified names of other classes are named for logger. 6. ConclusionLog4cxx has some notable features that allow C ++ to put them into their own toolbox. These features include flexible configuration capabilities, multiple output methods, and rich format control, outstanding Performance. If you need to debug and audit with logs in your development, you may need log4cxx. Finally, it is important that, as you can see, the use of log4cxx is so simple. If you are using the SDI or MDI program, follow these steps to use log4cxxx:1. Add the following lines to the header file of the CXXXApp class: # include <log4cxx/logger. h>
# Include <log4cxx/propertyconfigurator. h> using namespace log4cxx; 2. Add the public member variable to the CXXXApp class:
LoggerPtr rootLogger; 3. Add the following code at the bottom of CXXXApp: InitInstance:
PropertyConfigurator: configure ("log4cxx. properties"); rootLogger = Logger: getRootLogger (); 4. You can enter the log records as follows:
(CXXXApp *) AfxGetApp ()-> rootLogger-> info ("On OA Manage! ");
Related Article

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.