journal log4cxx encapsulation 、 Instance to explain 、 The configuration file log4cxx.properties

1. The role of logs

During the operation of the program , You need to record the running status of the program , It's easy to troubleshoot , Record data . You can quickly locate where the error occurred according to the log record , Then change the code . You can also set the log level , Show only severity level logs , Avoid generating a lot of logs .

2. Log4cxx How to use

(1)    from apache Download from the official website log4cxx Source code for compiling generation log4cxx.dll and log4cxx.lib file , Or download the compiled files directly from the Internet , Put these two files and the header folder log4cxx Copy to project . Set the header file and library file, including .

(2)    Logcxx.properties Profile Settings

This file is used to set the module of log file output , The level of log file output level, Larger file size for log output , The level limit of the module .Logcxx.properties The contents of the document are as follows :

# Set up root logger by TRACE Level , Used fa Two Appender

log4j.rootLogger=TRACE, fa

# Yes Appender fa Set it up :

# This is a file type Appender,

# Its output file (File) by ./output.log,

# Output mode (Append) For coverage mode ,

# Output format (layout) by 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] %-5p %.16c - %m%n

For a detailed introduction to configuration files, please refer to :

https://www.cnblogs.com/lowerCaseK/p/Log_properties.html

(3)log Header file definition

#ifndef ___LOG_DEFINE___
#define ___LOG_DEFINE___
#include <log4cxx/logger.h>
#include <log4cxx/logstring.h>
#include <log4cxx/propertyconfigurator.h>
#include<string>
#include <stdio.h>
#include <stdlib.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
#include <stdarg.h>
using namespace std;
#define SAFE_DELETE_ARRAY(v_para)\
do \
{\
if (NULL != v_para) {\
delete[] v_para;\
v_para = NULL;\
}\
} while (0)
//TRACE < DEBUG < INFO < WARN < ERROR < FATAL
typedef enum _LOG_LEVEL
{
LOG_TRACE_ = 0,
LOG_DEBUG_,
LOG_INFO_,
LOG_WARN_,
LOG_ERROR_,
LOG_FATAL_
}LOG_LEVEL;
#ifndef IN
#define IN
#endif
#ifndef OUT
#define OUT
#endif
/*
Write log function
IN const char* module,// stay log4cxx.properties There are a lot of append, This parameter is used to set the module , For example, in this example fa
IN const LOG_LEVEL level, The level of logging ERROR、INFO etc.
IN const char* file, Print log function call file
IN const char* function, Print log function
IN const int line, Print the line number of the log
IN const char* format,// Print log format Such as : "%s%d%f"
... // Variable parameter input
*/
void log4cxx_package(IN const char* module,IN const LOG_LEVEL level, IN const char* file, IN const char* function,
IN const int line, IN const char* format, ...);//
// Macro definition encapsulation ,__FILE__, __FUNCTION__, __LINE__ They are the file name of the print log 、 Function name , Line number
#define LOG(module,level, format,...) log4cxx_package(module,level, __FILE__, __FUNCTION__, __LINE__, format,__VA_ARGS__)
// Define macros at different levels
#define FIRE_ERROR(format,...) LOG("fa",LOG_ERROR_, format,__VA_ARGS__)
#define FIRE_INFO(format,...) LOG("fa",LOG_INFO_, format,__VA_ARGS__)
#define FIRE_TRACE(format,...) LOG("fa",LOG_TRACE_, format,__VA_ARGS__)
#define FIRE_DEBUG(format,...) LOG("fa",LOG_DEBUG_, format,__VA_ARGS__)
#define FIRE_WARN(format,...) LOG("fa",LOG_WARN_, format,__VA_ARGS__)
#define FIRE_FATAL(format,...) LOG("fa",LOG_FATAL_, format,__VA_ARGS__) //
// Initialize the logstore , Pass in logcxx.properties The name of the document
void log4cxx_init(IN const char* conffile);
// according to append Or module name to get the log pointer of the module . If it is root modular , Direct use Logger::getRootLogger(); obtain
LoggerPtr get_logger_ptr(IN const char* user);
#endif

(4) Log encapsulation source file implementation

#include "log.h"
static std::string ensure_log_complete(IN const char* format,IN va_list args)
{
if (NULL == format)
{
return "";
} int iNum = ;
unsigned int uiSize = ;
string strLog(""); char *pcBuff = new(std::nothrow) char[uiSize];
if (NULL == pcBuff)
{
return strLog;
} while(true)
{
memset(pcBuff, ,uiSize); iNum = vsnprintf(pcBuff, uiSize, format, args);
if ((iNum > -) && (iNum < (int)uiSize))
{
strLog = pcBuff;
SAFE_DELETE_ARRAY(pcBuff); return strLog;
} // If the string value is larger than the default assignment , Then allocate more space
uiSize = (iNum > -)?(int)(iNum + ):(uiSize * );
SAFE_DELETE_ARRAY(pcBuff); pcBuff = new(std::nothrow) char[uiSize];
if (NULL == pcBuff)
{
return strLog;
}
} SAFE_DELETE_ARRAY(pcBuff); return strLog;
}

/*
Write log function
IN const char* module,// stay log4cxx.properties There are a lot of append, This parameter is used to set the module , For example, in this example fa
IN const LOG_LEVEL level, The level of logging ERROR、INFO etc.
IN const char* file, Print log function call file
IN const char* function, Print log function
IN const int line, Print the line number of the log
IN const char* format,// Print log format Such as : "%s%d%f"
... // Variable parameter input
*/

void log4cxx_package(IN const char* module,IN const LOG_LEVEL level, IN const char* file, IN const char* function,

 IN const int line, IN const char* format, ...)
{
if (level > LOG_FATAL_ || level < LOG_TRACE_)
{
return;
} if (NULL == file || NULL == function || NULL == format)
{
return;
}
LoggerPtr pLogger=NULL;
if (module!=NULL)
{
pLogger=get_logger_ptr(module);
}
if(pLogger==NULL)
{
pLogger= Logger::getRootLogger();
} char acTmp[] = { };
sprintf(acTmp,"%d",line); va_list args;
std::string strLog;
strLog = "[" + std::string(file) + ":" + std::string(function) + "(" + std::string(acTmp) + ")] "; va_start(args, format);
strLog += ensure_log_complete(format, args);
va_end(args); switch (level)
{
case LOG_TRACE_:
LOG4CXX_TRACE(pLogger, strLog.c_str());
break;
case LOG_DEBUG_:
LOG4CXX_DEBUG(pLogger, strLog.c_str());
break;
case LOG_INFO_:
LOG4CXX_INFO(pLogger, strLog.c_str());
break;
case LOG_WARN_:
LOG4CXX_WARN(pLogger, strLog.c_str());
break;
case LOG_ERROR_: LOG4CXX_ERROR(pLogger, strLog.c_str());
break;
case LOG_FATAL_:
LOG4CXX_FATAL(pLogger, strLog.c_str());
break;
default:
break;
} return;
} void log4cxx_init(IN const char* conffile)// Initialize the logstore
{
// Read configuration file
using namespace log4cxx;
PropertyConfigurator::configure(File(conffile));
return ;
} LoggerPtr get_logger_ptr(IN const char* user)// Get the log module pointer
{
// establish logger
return Logger::getLogger(user);
}

(5) Examples of program usage

log4cxx_init("log4cxx.properties");// Initialize the logstore 
// Call macro definition to achieve different levels of log output
FIRE_ERROR("fjqfqfquhfwuhuquw%d%s",,"erqeqr");
FIRE_INFO("fjqfqfquhfwuhuquw%d%s",,"erqeqr");
FIRE_WARN("fjqfqfquhfwuhuquw%d%s",,"erqeqr");
FIRE_FATAL("fjqfqfquhfwuhuquw%d%s",,"erqeqr");

(6) After the program starts , A file named output.log Log file , In the log file, the log day will be printed

2018-04-07 17:27:21,805 [0x00001f68] ERROR fa - [StockViewDlg.cpp:CStockViewDlg::OnInitDialog(108)] fjqfqfquhfwuhuquw12345erqeqr
2018-04-07 17:27:21,805 [0x00001f68] INFO fa - [StockViewDlg.cpp:CStockViewDlg::OnInitDialog(109)] fjqfqfquhfwuhuquw12345erqeqr
2018-04-07 17:27:21,805 [0x00001f68] WARN fa - [StockViewDlg.cpp:CStockViewDlg::OnInitDialog(110)] fjqfqfquhfwuhuquw12345erqeqr
2018-04-07 17:27:21,805 [0x00001f68] FATAL fa - [StockViewDlg.cpp:CStockViewDlg::OnInitDialog(111)] fjqfqfquhfwuhuquw12345erqeqr

I made up a stock monitoring software , It has the following functions , Interested friends can download ;

(1)   Unit monitoring . Monitoring real-time changes in individual units , It can monitor the trading of individual large orders 、 To pull up and down rapidly 、 Main entry and exit 、 Top and bottom of Stock Alert . Highest point detected 、 The lowest point 、 Main entry point 、 Main exit point 、 Pull up a little fast 、 A sharp drop , Give voice or voice reminders , Don't look at the market any more , Give you more free time ;

(2)   Market monitoring . Monitor the trend of the market , Adoption of Shanghai card 、 Deep evidence 、 The comprehensive index of the three indexes of entrepreneurship is taken as the trend of the market . And real-time monitoring of the highest and lowest points of the market 、 The turning point in the middle .

(3)   Stock recommendation . It can also analyze the long-term or short-term trend of historical data , For the stock market 3 More than 1000 stocks are analyzed and compared , Pick stocks that are up well , In order of growth rate from large to small , Recommend to you stocks that are rising well ;

Download address :

1.0.3 edition ( Fix the market index crash defect ) Download address :

link :https://pan.baidu.com/s/1BJcTp-kdniM7VE9K5Kd3vg Extraction code :003h

update link :

https://www.cnblogs.com/bclshuai/p/10621613.html

journal log4cxx encapsulation 、 Instance to explain 、 The configuration file log4cxx.properties More articles about

  1. log4CXX Second articles --- The configuration file (properties file ) Detailed explanation

    One .Log4j brief introduction Log4j There are three main components :Loggers( Recorder ),Appenders ( output source ) and Layouts( Layout ). It can be simply understood as log category , Where the log is to be output and in what form . Comprehensive envoy ...

  2. Java journal ( One ):log4j And .properties The configuration file

    Log is an indispensable part of application software ,Apache Open source projects for log4j It's a powerful logging component , Provide convenient logging , stay Apache Website jakarta.apache.org/log4j It's free to download to Log4j ...

  3. springboot Configuration file application.properties Configuration details of , Data source configuration

    pring Boot A global configuration file is used application.properties, Put it in src/main/resources Directory or classpath /config Next .Sping Boot Global configuration file for ...

  4. spring Examples of transaction propagation mechanism

    http://kingj.iteye.com/blog/1680350   spring Examples of transaction propagation mechanism Blog classification :   spring java experience adventure     Day review spring Transaction processing mechanism of , summary ...

  5. [ turn ]Scrapy Simple introduction and example explanation

    Scrapy Simple introduction and example explanation Chinese document :   http://scrapy-chs.readthedocs.io/zh_CN/0.24/ Scrapy It's a way of crawling website data , Applications written to extract structural data ...

  6. [ Re posting ]linux General Command (linux From basic command to mastery + Instance to explain + Continuous updating + Order memo + Interview review )

    linux General Command (linux From basic command to mastery + Instance to explain + Continuous updating + Order memo + Interview review ) https://www.cnblogs.com/caozy/p/9261224.html The summary is very good ...

  7. catalina.out Examples of solving log inflation problems , Log facade commons-logging Practice

    Statement : Moved from myself CSDN Blog https://blog.csdn.net/u013365635 When I was in the company , There's a problem ,2 A module A.B Tomcat Medium catalina.out And catalina ...

  8. vue Examples explain vue-router Use

    Example explanation series vue-router Use Let's summarize vue-router The basic framework used : 1. Install and introduce vue-router install :npm install vue-router --save-dev ...

  9. Example explanation is based on React+Redux The front-end development process of

    Original address :https://segmentfault.com/a/1190000005356568 Preface : In the frontiers of the moment ,react and redux In full swing ,react stay github Of s ...

Random recommendation

  1. entityframework Learning notes --004- The relationship between no load and load

    1. No load (with NO Payload) Many to many relationship modeling of In the database , There is a case where two tables are linked by one linked table . Linked tables only contain foreign keys that connect two tables to form a many to many relationship , You need to import these two many to many tables into the entity framework model ...

  2. Android And ViewHolder usage

    http://www.cnblogs.com/mengdd/p/3254323.html (zhuan) http://blog.csdn.net/mrzhang_happy/article/deta ...

  3. DataSet The data is exported as Excel file ( Every DataTable For one Sheet)

    Web In the project , Many times, it is necessary to export the query data set as Excel Functions of documents , Most of the time, I don't want to add a pair of Office Component related DLL References to , And sometimes even by Office The impact of different versions , Results on different servers ...

  4. poj 2728 Desert King( Optimal proportion spanning tree )

    #include <iostream> #include <cstdio> #include <cmath> #include <cstdlib> #i ...

  5. Linux In the environment MySQ Import and export MySQL Of sql file

    To import or export files from the server, you need to use tools to transfer them to your computer , Recommended winscp, And xshell Use it with 1  Import database The two methods . First, build an empty database mysql>create database abc ...

  6. utilize StackExchange.Redis and Log4Net Build a log queue

    brief introduction : This article is a simple demo Used to show the use of StackExchange.Redis and Log4Net Build a log queue , Provide some ideas for high concurrency log processing . 0. Download and install first Redis service , Then start the service in the service list (R ...

  7. day81

    Look back yesterday : Look back yesterday : auth Components : - verification :authenticat(request,username=') - Sign in :login(request,user) - Cancellation :logout(request), ...

  8. ASP.NET MVC 4 ( Nine ) Model binding

    Model binding refers to MVC Sent from the browser HTTP Create... For us in the request .NET object , stay HTTP Request and C# It's a bridge . One of the simplest examples of model binding is controller with parameters action Method , For example, we can register such a path mapping : ...

  9. The first 81 speak :Scala in List The construction and type constraints of 、 Covariance 、 Lower bound

    Let's learn about it today scala in List The construction and type constraints of . Let's take a look at the code package scala.learn /** * @author zhang */abstract class Big ...

  10. c++Builder XE6 MD5 encryption algorithm BASE64 URL code

    xe6,xe7 BASE64XE6 MD5 encryption algorithm Delphifunction MD5(const texto: string): string; var idmd5: TIdHashMessage ...