Using the Apache Log4cxx Log service in C + + __c++

Source: Internet
Author: User
Tags log4j
Abstract Log4cxx is one of the subprojects of the Open source project Apache Logging Service, which is used to provide log functionality for C + + programs so that developers can debug and audit the target program. This paper introduces the usage and configuration of log4cxx, and gives an example which can be started quickly. Finally, some practical suggestions are given for the log service. 1. IntroduceLog4cxx is one of the subprojects of the Open source project Apache Logging Service, a well-known log4j C + + transplant version of the Java community, which provides logging capabilities for C + + programs so developers can debug and audit the target program. More information about Log4cxx can be obtained from the website of the Apache Loggin service http://logging.apache.org. The current stable version is 0.9.7, and this article and the sample code are all based on this version. In addition, the compilation environment for the sample code is Microsoft Visual C + +. Net 2003 in the Windows environment. The sample code for this article can be downloaded here, which also contains the precompiled Log4cxx library files. 2. Integrated Log4cxx to the IDETo use Log4cxx, you first need to integrate it into your project development environment. The following is described for Microsoft Visual C + +. Net 2003 in Windows environments, and the configuration information for other environments refer to the official documentation. To get Log4cxx to work for you, you usually need the following steps: L GET the software package: Get log4xx source code; L Compile: Build library file; L Project environment settings: Join LOG4CXX support. 2.1 Getting PackagesPlease obtain the appropriate version from the official website. It can also be obtained directly from the link below (the direct link address may not be valid forever): http://mirror.vmmatrix.net/apache/logging/log4cxx/log4cxx-0.9.7.tar.gz When the download is complete, unzip it to the appropriate directory, because we need to use the package in the next step, including compiling and copying the necessary files. 2.2 CompilingThe original release package does not contain compiled code, this job requires us to do it ourselves. Open your IDE and load the works in the following directory: L Msvc/static: This project produces log4cxx static link libraries (Lib4cxx.lib and Lib4cxxs.lib); l Msvc/dll: the project produces log4cxx Dynamic link library (lib4cxx.dll). Usually, the project can be successfully compiled through. View the output directory and find the generated library files for use in the next step. 2.3 Project Environment settingsFirst open a project in the IDE that requires logging functionality, or create a new project for experimental purposes to set it up. First you need to set the log4cxx include file. These files are located in the Include/log4cxx directory of the LOG4CXX software package. Check out the contents listed in the "Tools-> options-> Project->vc++ directory-> include files" in your VC + + IDE to determine how you would add these include files: L Copy the include/log4cxx directly to the defined inclusion File directory. It makes sense to think of log4cxx as a system service, because you can use it in a standard library, for example: #include <log4cxx/logger.h> l Add a include path to a file located outside the IDE Directory. You can simply point to the Log4cxx package directory that was formed after decompression in 2.1. The next step is to set up the Log4cxx library that is generated in section 2.2. It depends on how you use the library: static links or dynamic links. L Static link situations need to do the following: Define Log4cxx_static macros for the precompiled, set location as "Project-> properties-> Configuration Properties->c/c++-> preprocessor-> Preprocessor Definitions" ; Specify the dependent library Lib4cxxs.lib and ws2_32.lib for the linker, set the location to the project-> properties-> Configuration Properties-> linker-> input-> additional dependencies. L only need to specify the dependent library Lib4cxxs.lib for the linker in the case of dynamic link, set the way above. 3. Sample CodeThis section shows one of the simplest log4cxx examples so that you can quickly understand it. The example creates a log service on a feature that enables the necessary control through a configuration file and outputs information to both the file and the console at the same time. On implementation, we used a simple console program and used log4cxx in the form of a dynamic-link library. 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. Notice the way we use the dynamic connection interface here. 2 Add the code to implement the log function in Logdemo.cpp. The complete code list is as follows:

#include "stdafx.h" #include <log4cxx/logger.h> #include <log4cxx/propertyconfigurator.h> using namespace   Log4cxx; int _tmain (int argc, _tchar* argv[]) {//Load Log4cxx configuration file, which uses the property file Propertyconfigurator::configure ("Log4cxx.propert         ies ");         Obtain a Logger, where the rootlogger loggerptr Rootlogger = Logger::getrootlogger () is used; Send an INFO level output request Log4cxx_info (Rootlogger, _t ("It does work"); Rootlogger->info ("It did work") (_t); With the above sentence function quite return 0; }

Compile the project in debug mode and debug the program until it succeeds. 3 Create a new text file named Log4cxx.properties, and type the following:

# set Root logger to DEBUG level, using CA and FA two Appender log4j.rootlogger=debug, CA, FA #对Appender FA set: # This is a file type of Appender, # its output text (File) is./output.log, # Output mode (Append) is overlay, # output format (layout) is Patternlayout log4j.appender.fa= Org.apache.log4j.FileAppender Log4j.appender.fa.file=./output.log Log4j.appender.fa.append=false Log4j.appender.fa.layout=org.apache.log4j.patternlayout log4j.appender.fa.layout.conversionpattern=%d [%t]%-5p%. 16c-%m%n #对Appender CA Set: # This is a console type of Appender # output format (layout) for Patternlayout log4j.appender.ca=org.apache.log4j.cons Oleappender Log4j.appender.ca.layout=org.apache.log4j.patternlayout log4j.appender.ca.layout.conversionpattern=% d [%t]%-5p%.16c-%m%n

4) Copy Log4cxx.dll to output directory. In a dynamic link, the application needs to be able to locate the library file. 5 Run the generated Logdemo.exe file, look at the results of the operation and see if our work has been effective. If all goes well, you should see output similar to the following in both the console and the output file:

2006-06-02 16:09:50,609 [2528] INFO root-it does work.

4. Architecture 4.1 Core ClassesLog4cxx has three key components, they are loggers, appenders and layouts. Logger is the core class of Log4cxx, as long as the log operation is performed, Looger has a hierarchy, and the topmost level is rootlogger;logger. Each logger can attach multiple appender. Appender represents the target of log output, such as output to files, consoles, and so on. For each type of appender, you can format it by layout. These three types of components are shown as follows (does not represent class relationships): (TODO: Here are three components described separately)4.2 Configuration ClassIn addition, classes that are used in use include Basicconfigurator, Propertyconfigurator, and Domconfigurator, which are used to configure Log4cxx. Where: Basicconfigurator provides a simple configuration, including the use of Consoleappder as 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: Description of configuration content here)5. Practical GuidanceWhether to use logs in a project, and how to use them, is a technical choice that developers need to make, often involving the performance of the system, the purpose of using the log, and so on. Some of the ways we use the journal are that the industry has accumulated years of experience, and some of it is purely a matter of personal preference. 1 when to use the log usually, the role of the log is to debug and audit, if your project has special needs for this, you can consider using the log. For debugging, it is commonly used where the IDE debugger cannot be reached. Some common scenarios include: debugging distributed components. On a server-side component, the client's call is required to verify that it is working correctly, and the error is diagnosed using the log's output as an auxiliary tool. link library debugging. This method works well in situations where you cannot track into external libraries. Debugging in the production environment. The production environment usually refers to the product in the customer place in the state of formal operation, in the case of problems, developers are often not on the scene, with the help of log output error judgment is a very effective means. For the audit application, it needs to depend on the specific circumstances, the program-level record ability, no doubt can be used as an effective complement to the business-level audit means. In either scenario, Log4cxx is capable of working, depending on its flexible configuration and various types of output. 2 Performance problems close the log, set the log off by configuration file, and open the output command that uses macros instead of logger to selectively output the log. Establish a hierarchy of logger to output targets according to the level selective output. Select the appropriate output format to minimize the output target. Using simplelayout will achieve the same speed as std::cout. 3 other use of the fully qualified name of the class logger named6. ConclusionSome of the salient features of Log4cxx allow C + + to put them into their toolbox, which includes flexible configuration capabilities, multiple output methods, rich formatting controls, and excellent performance. If you need to use a log for debugging and auditing in your development, you may need to log4cxx. Finally, the important point is that, as you can see, the use of log4cxx is so simple.

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.