Logs in C ++, Java, and JavaScript)
Logging of programming ideas
What is log?
I believe you will write your thoughts in your diary, or use space and Weibo to record your daily joys and sorrows! There are similar things in the program that record the daily whereabouts of his master (Application). His name is log ). A diary is a notebook of human life, and a log is a notebook of program running status.
As the name suggests, logs (logs are all called logs later) are used to record the daily running status of programs, such as exceptions of programs or key points, important data or transactions. Every day does not mean that every day is recorded. It can always be accompanied by the running of the program. As long as the program is running, the logs of every day are recorded in the same file, logs are separated by different file names every day.
Next let's take a look at the log recording methods in C ++, Java, and JavaScript.
Add log to program
Log in C ++:
C ++ has a lot of libraries that record logs. log4cpp (log4cxx) and Google Glog are commonly used. The following describes how to use log4cpp (log4cxx.
Log4cxx is an open-source library of the apache Software Foundation. It is a cross-platform log processing Tracking Project transplanted from log4j. Log4cxx downloaded from the official website only has the source code and needs to be compiled by yourself.
Log4cxx Compilation
.
.
3. Rename the apr-1.2.11 to apr, rename the apr-util-1.2.10 to apr-util, and copy the apr and apr-util to the apache-log4cxx-0.10.0 root directory.
4.run cmd.exe with the Administrator's ID and navigate to the current apache-log4cxx-0.10.0 directory of log4cxx, execute the following command:
Configure Configure-aprutil |
When configure-aprutil is executed, the system prompts: "'sed 'is not an internal or external command, or a program or batch file that can be run ". This is because the sed command in Linux is used in the configure-aprutil.bat file and the sed command cannot be found in windows. There are several solutions: 1. download a sed for windows tool. 2. use Cygwin (UNIX-like simulated environment running on windows platform), and then run the configure-aprutil.bat; 3. manually modify.
Or manually change it. \ apr-util \ include \ apu. change # define APU_HAVE_APR_ICONV 1 under hw to # define APU_HAVE_APR_ICONV 0. change # define APR_HAS_LDAP 1 under \ apr-util \ include \ apr_ldap.hw to # define APR_HAS_LDAP 0.
5. open projects/log4cxx with Visual Studio VC6 or later. dsw, in turn will ask you to choose the apr, aprutil, xml project working directory, find the corresponding apr in the subdirectory of the apache-log4cxx-0.10.0. dsp, aprutil. dsp, xml. open the dsp file.
6. Select log4cxx as the Active project and compile it.
7. during compilation, the following error may be reported: the file cannot be opened: "apr. h and apu. h ", find the corresponding apr. hw is renamed as apr. h, apu. h. rename it to apu. h.
Use of log4cxx
<1> simple example:
Create a project, set the log4cxx header file path and lib library path, and load the log4cxx. lib file. The test code is as follows. The log information is output in the command line.
# Include "stdafx. h "# include" log4cxx/logger. h "# include" log4cxx/basicconfigurator. h "# include" log4cxx/helpers/exception. h "using namespace std; using namespace log4cxx; using namespace log4cxx: helpers; int main () {// @ todo redirects to the file LoggerPtr logger (Logger :: getLogger ("LogTest"); // initialize the configuration BasicConfigurator: configure (); // output the DEBUG-level log LOG4CXX_DEBUG (logger, "debug log "); // output TRACE-level logs LOG4CXX_TRACE (logger, "debug log"); // output INFO-level logs LOG4CXX_INFO (logger, "info log "); // output logs of the WARN level LOG4CXX_WARN (logger, "debug log"); // output logs of the ERROR level LOG4CXX_ERROR (logger, "debug log "); // output the FATAL-level log LOG4CXX_FATAL (logger, "debug log"); // ASSERT determines whether the condition is correct. If the condition is false, the output information LOG4CXX_ASSERT (logger, 1 = 2, "1 = 2"); return 0 ;}
Note: When I use VC6.0 to compile the log4cxx source code and use the log4cxx library in VS2010, the following error occurs during compilation: unresolved external symbol "_ declspec (dllimport) public: void _ thiscall log4cxx: Logger: forcedLog
This is because the libraries compiled by different compilers may be different. To be used on VS2010, you need to re-compile the source code on VS2010.
<2>. Set the configuration file:
If you want to output log information to a file or to both the command line and file, modify the configuration file.
Log4cxx. properties:
# Set the root logger to the DEBUG level and use the ca and fa Appenderlog4j. rootLogger = DEBUG, leleappender, fileAppender # Set the Appender fileAppender (output to file): # This is a file-type Appender, log4j. appender. fileAppender = org. apache. log4j. fileAppender # output log information. /log4cxxTest. log, log4j. appender. fileAppender. file =. /log4cxxTest. log # The output method is to append log4j to the end of the file. appender. fileAppender. append = true # Set the output format (layout) to PatternLayoutlog4j. appender. fileAppender. layout = org. apache. log4j. patternLayout # log4j. appender. fileAppender. layout. conversionPattern = % d [% t] %-5 p %. 16c-% m % n # Set log4j for Appender consoleAppender (output to the console. appender. leleappender = org. apache. log4j. consoleAppender # This is a console-type Appenderlog4j. appender. leleappender. layout = org. apache. log4j. patternLayout # The output format (layout) is PatternLayoutlog4j. appender. leleappender. layout. conversionPattern = % d [% t] %-5 p %. 16c-% m % n
Code:
# Include "stdafx. h "# include" log4cxx/logger. h "# include" log4cxx/PropertyConfigurator. h "using namespace std; using namespace log4cxx; using namespace log4cxx: helpers; int main () {// use the specified file to load and prepare log4cxx: PropertyConfigurator :: configure ("E:/Test/log4cxx. properties "); // create logger LoggerPtr logger = Logger: getLogger (" test "); // output the DEBUG-level log LOG4CXX_DEBUG (logger," debug log "); // output TRACE-level logs LOG4CXX_TRACE (logger, "debug log"); // output INFO-level logs LOG4CXX_INFO (logger, "info log "); // output logs of the WARN level LOG4CXX_WARN (logger, "debug log"); // output logs of the ERROR level LOG4CXX_ERROR (logger, "debug log "); // output the FATAL-level log LOG4CXX_FATAL (logger, "debug log"); // ASSERT determines whether the condition is correct. If the condition is false, the output information LOG4CXX_ASSERT (logger, 1 = 2, "1 = 2"); return 0 ;}
Log in Java:
There are three main ways to add logs to the project in Java: one is to use the java. util. logging package in JDK, the other is log4j, and the other is commons-logging. Log4j and commons-logging are both open-source projects of the apache Software Foundation. The differences between the three methods are as follows:
Java. util. logging, a class in the JDK standard library, is a feature package for logging added after JDK 1.4.
Log4j is the most powerful way to record logs. You can configure the log destination and format by configuring the. properties or. xml file.
Commons-logging, the most comprehensive and common logging method, is a log interface in Java and is generally used with log4j. The built-in SimpleLog can be used for logging.
1. Java. util. logging
[Example 1.1]: simple use of logs
Package lwf. log. test; import java. util. logging. logger; public class LogTest {static String strClassName = LogTest. class. getName (); static Logger logger = Logger. getLogger (strClassName); public static double division (int value1, int value2) {double result = 0; try {result = value1/value2;} catch (ArithmeticException e) {logger. warning ("the divisor cannot be 0. "); e. printStackTrace ();} return result;} public static void main (String [] args) {System. out. println (division (5, 0 ));}}
Result:
In this example, you can see that the date and time, class name, method name, and "[warning] divisor cannot be 0." Are output on the console.
Logger is a class in the Java Logging API. The Logger. getLogger method creates a Logger instance. Each Logger instance must have a name. Generally, the class name is used to define the Logger instance.
The logger. warning method is used to output log information. Besides warning, it also includes severe and info. We can change [Example 1] to output various log information.
[Example 1.2]: Log Level
Public static double division (int value1, int value2) {double result = 0; try {result = value1/value2;} catch (ArithmeticException e) {logger. severe ("[severe] division cannot be 0. "); logger. warning ("[warning] division cannot be 0. "); logger.info (" [info] The divisor cannot be 0. "); logger. the addition of config ("[config] cannot be 0. "); logger. fine ("[fine] The divisor cannot be 0. "); logger. finer ("[finer] division cannot be 0. "); logger. finest ("[finest] division cannot be 0. "); e. printStackTrace ();} return result ;}
Result:
The Java Logging API provides seven log levels to control output. These seven levels are:
Level |
SEVERE |
WARNING |
INFO |
CONFIG |
FINE |
FINER |
FINEST |
Call Method |
Severe () |
Warning () |
Info () |
Config () |
Fine () |
Finer () |
Finest () |
Meaning |
Severe |
Warning |
Information |
Configuration |
Good |
Better |
Best |
However, in the above example, we can see that only logs of the SEVERE, WARNING, and INFO levels are output, and there is no similar output of log information of each level. This is because the default log output level is info, that is, only info or above is output, and below it is not output. How can I modify this setting?
Log preparation:
1. Code settings
SetLevel () is used. However, this method cannot change the console level, but can only change the log level output to the file.
2. Modify logging. properties
The default external configuration file is the lib/logging. properties file in JRE. You can open this file and modify the following two actions:
. Level = ALL //... Java. util. logging. lelehandler. level = ALL |
This method affects all jre users.
In order not to affect all users, we can also read the specified configuration file through the readConfiguration (InputStream ins) of LogManager.
[Example 1.3]: LogManager logs
Package lwf. log. test; import java. io. IOException; import java. io. inputStream; import java. util. logging. fileHandler; import java. util. logging. handler; import java. util. logging. level; import java. util. logging. logManager; import java. util. logging. logRecord; import java. util. logging. logger; import java. util. logging. simpleFormatter; public class LogTest {static String strClassName = LogTest. class. getName (); static Logger logger = Logger. getLogger (strClassName); static LogManager logManager = LogManager. getLogManager (); static {InputStream inputStream = null; try {// read the preparation file inputStream = LogTest. class. getClassLoader (). getResourceAsStream ("log. properties "); logManager. readConfiguration (inputStream); // Add LoggerlogManager. addLogger (logger);} catch (SecurityException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace () ;}} public static double division (int value1, int value2) {double result = 0; try {result = value1/value2;} catch (ArithmeticException e) {logger. severe ("[severe] division cannot be 0. "); logger. warning ("[warning] division cannot be 0. "); logger.info (" [info] The divisor cannot be 0. "); logger. the addition of config ("[config] cannot be 0. "); logger. fine ("[fine] The divisor cannot be 0. "); logger. finer ("[finer] division cannot be 0. "); logger. finest ("[finest] division cannot be 0. "); e. printStackTrace ();} return result;} public static void main (String [] args) {System. out. println (division (5, 0 ));}}
Log. properties:
# "Handlers" specifies a comma separated list of log Handler # Handlers = java. util. logging. lelehandler Handlers = java. util. logging. FileHandler # Default logging level. . Level = CONFIG # Default file output is in "E: \ Test" directory. Java. util. logging. FileHandler. pattern = E:/Test/Log % u. log Java. util. logging. FileHandler. limit = 50000 Java. util. logging. FileHandler. count = 1 Java. util. logging. FileHandler. formatter = java. util. logging. SimpleFormatter # Limit the message that are printed on the console to CONFIG and above. Java. util. logging. lelehandler. level = CONFIG Java. util. logging. lelehandler. formatter = java. util. logging. SimpleFormatter # Facility specific properties. Provides extra control for each logger. # For example, set the com. xyz. foo logger to only log SEVERE messages: Com. xyz. foo. level = SEVERE |
In this way, you can define the preparation file by yourself. You can view the output Log File Log0.log under E: \ Test.
The relationships between classes in the java. util. logging package are as follows:
References:
Http://blog.csdn.net/dl88250/article/details/1843813
2. log4j
1. Import the project string to the jar package of log4j
For example, right-click the project name in Eclipse, Build Path \ Add Libraries, and Add a group of your own jar packages. The project structure is as follows:
2. modify the configuration file of log4j and set the log output level and format.
Log4j has five levels of logs: FATAL (severe), ERROR (ERROR), WARN (warning), INFO (information), and DEBUG (debugging ).
3. Add logs in the project code.
[Example 2.1]
Log4j. properties:
# Set log level: show debug, info, error Log4j. rootLogger = DEBUG, A1 # A1 is set to be a ConsoleAppender which outputs to System. out. # Log4j. appender. A1 = org. apache. log4j. leleappender Log4j. appender. A1 = org. apache. log4j. FileAppender # A1 uses PatternLayout. Log4j. appender. A1.layout = org. apache. log4j. PatternLayout # Out Log4j. appender. A1.File = E:/test/log4j. log # Set log output format's style Log4j. appender. A1.layout = org. apache. log4j. TTCCLayout |
Code:
Package lwf. log. test; import org. apache. log4j. logger; public class Log4jTest {private static Logger logger = Logger. getLogger (Log4jTest. class); public static void main (String [] args) {System. out. println ("This is log4j test. "); // record debug-level information logger. debug ("This is debug message. "); // record the info-level information logger.info (" This is info message. "); // record error-level information logger. error ("This is error message. ");}}
For the use and preparation of log4j, see: http://blog.csdn.net/luoweifu/article/details/43638495
3. commons-logging
Commons-logging provides a Log interface, which is created for developers who need to build components or libraries that use different Log architectures in different environments, this includes the log architecture of Apache Log4j and Java log. Abstract The Log information into the commons-logging Log interface, and the commons-logging determines which Log architecture to use at runtime. Because of the powerful functions of Log4j, commons-logging is generally used with Log4j, which is almost a standard tool for Java logs.
Commons-logging has two basic abstract classes: Log (Basic recorder) and LogFactory (responsible for creating Log instances ). When the commons-logging.jar is added to the CLASSPATH (typically placing the commons-logging.jar in the WebContent \ WEB-INF \ lib directory under the web project), it will reasonably guess what log tool you want to use, then, you do not need to perform any settings. The default LogFactory discovers and determines which log tool will be used (in order, the search process will stop when the first tool is found. This order is very important ):
00001. Search for the value of the Configuration Attribute org. apache. commons. logging. Log in the current factory.
00002. Search for the value of org. apache. commons. logging. Log in the system attribute.
00003. If the classpath of the application contains log4j, use the related wrapper class (Log4JLogger)
00004. If the application runs in the jdk1.4 system, use the related packaging class (Jdk14Logger)
00005. Use simple log packaging class (SimpleLog)
Use commons-logging in combination with log4j:
Project directory structure:
Common-logging.properties:
# Use commons-logging default SimpleLog # Org. apache. commons. logging. Log = org. apache. commons. logging. impl. SimpleLog # Use log4j Org. apache. commons. logging. Log = org. apache. commons. logging. impl. Log4JCategoryLog # JDK1.4 Logger # Org. apache. commons. logging. Log = org. apache. commons. logging. impl. Jdk14Logger |
Code:
Package lwf. log. test; import org. apache. log4j. logger; public class Log4jTest {private static Logger logger = Logger. getLogger (Log4jTest. class); public static void main (String [] args) {System. out. println ("This is log4j test. "); // record debug-level information logger. debug ("This is debug message. "); // record the info-level information logger.info (" This is info message. "); // record error-level information logger. error ("This is error message. ");}}
Refer:
Http://www.cnblogs.com/xwdreamer/archive/2011/12/28/2304598.html
Http://shift8.iteye.com/blog/1316802
Log in JavaScript: JavaScript is an explanatory language. It is generally used as a browser script in the web Front-end. There are relatively few log records, such as log4js. I will try again later ......
Log Functions
1. program error report
Generally, an error report dialog box is automatically displayed when an application encounters an exception or crash. You can choose whether to submit the report. If the user submits an error Report, the application developer can view the cause of the program error based on the report log information to better improve the program.
2. Count the access volume and number of users of the program.
Although this is not the best method, it is also a feasible method.
Application scenarios of log
1. Exceptions, often used in combination with try... catch...
2. output the necessary information to replace the command line output.
PS: the Spring Festival is approaching. I wish you a happy new year. It will be more beautiful, healthier, more progressive, and more intelligent in the New Year!
If you have any questions or thoughts, please give feedback in the comments. Your feedback is the best Reviewer! Due to my limited technical skills and capabilities, if this blog post contains errors or deficiencies, please forgive me and give your valuable suggestions!
======================================= Review of the series of programming ideas ==================
Exception Handling in programming ideas
Regular Expressions of programming ideas
Programming idea iterator
Recursion of programming ideas
Callback of programming ideology