glog Google open source logging library

glog to google open source library for implementing application-level logging, based on C ++ provides help macro definitions Stream flow and various logging interface that provides to the console, logging files; 
   the following based on the windows platform, the most basic using frame, analyzes the source projects sample code; 
   #define GOOGLE_GLOG_DLL_DECL
  #define GLOG_NO_ABBREVIATED_SEVERITIES 
  #include " GLog / logging.h " 
  int main ( int argc, char * the argv []) 
  { 
    FLAGS_log_dir    = " ./glog_log " ; Google: : InitGoogleLogging (the argv [ 0 ]); 
      the LOG (the INFO) << " Found " << 15 << "   Cookies" ; 
      Google :: ShutdownGoogleLogging (); 
      return  0 ; 
  } 
The basic example code, typically required when the pre-declared statically linked libglog_static.lib macro GOOGLE_GLOG_DLL_DECL, comprising in addition before the header files need logging.h Declaration Macros 
GLOG_NO_ABBREVIATED_SEVERITIES, because sometimes a user may use the windows.h header file and the header file placed after logging.h did not declare WIN32_LEAN_AND_MEAN 
or GLOG_NO_ABBREVIATED_SEVERITIES, this will lead to the current macro ERROR glog in conflict, we need to declare in loggging.h before the declaration; 
Google :: InitGoogleLogging (argv [ 0 ]), the statement initialize the log repository (in fact a short file name field segment initialization log file); 
FLAGS_log_dir: set the log file directory (the directory should exist before, or else unable to save the log); 
lOG (iNFO): log level macros, logging information; 
Google :: ShutdownGoogleLogging: close the log database, the release of internal resources; 
over the entire basic operation flow, then we were defined within each macro statement, in-depth analysis of the structure definitions; 

conf ig.h:
  Configuration-related, mainly inside the google namespace declaration, import and export related to the macro, the macro used in the import and export dll, so the need loggging.h before the macro statement GOOGLE_GLOG_DLL_DECL If using a static link; 

commandlineflags.h: 
  internal statement a few species macro ( BOOL , Int32, String declarations and definitions of specific internal GLog, respectively DECLARE_bool, DECLARE_int32, DECLARE_string) placed after each macro expansion namespace, after to DECLARE_bool (name) {Example FLB extended namespace BOOL FLAGS_name }, defined DEFINE_bool (name, value, meaning) is expanded FLB {namespace BOOL the FLAGS name _ ## (a); char FLAGS_no ## name;} and environment variables acquired and transformed EnvToString, EnvToBool, EnvToInt; 

googleinit.h: 
  defined inside the class GoogleInitializer initializer (tracking source code, it is necessary to obtain an operating environment variable current username implemented as MyUserNameInitializer function to initialize g_my_user_name global variable), in addition to macro REGISTER_MODULE_INITIALIZER 
(name, body) to declare glog application process initialize global variables when loading, by constructing Bureau variable call the global static functions to achieve call in advance before the entry point function "main" interfaces (in fact, only in utilities);

log_severity.h: 
    it defines several log severity level LogSeverity: GLOG_INFO, GLOG_WARNING, GLOG_ERROR, GLOG_FATAL, NUM_SEVERITIES front and four respectively INFO, WARNING, ERROR, FATAL as a parameter the user to save the log level use, namely information, warning , error, fatal, in addition to use for DFATAL_LEVEL different levels in different logging modes, DEBUG mode bit fATAL, RELEASE mode eRROR; Definition of global variables LogSeverityNames, respectively, to identify the level of the above types of logs string name; 

mutex.h : 
    inside the package under Windows CRITICAL_SECTION critical areas for achieving Mutex lock mechanism, and the package automatically lock MutexLock, read-write locks ReaderMutexLock, WriterMutexLock; internal glog currently only used WriterMutexLock, (in fact ReaderMutexLock consistent with the internal WriterMutexLock); 

port.h : 
    from google partial copies of -perftools, mainly for internal VC compiler under windows service, the main achievement of the types of heavy facilitate unified statement related to the use, such as C-run time of the file the I / O-related, file copy, character string Than, Sleep, string formatted output, system processes, threads, localtime_r, strerror_r, all of which are fundamental to an existing interface and simple renaming process to facilitate cross-platform unified interface, call it;
 
vlog_is_on.h:
    Providing the parameters from the control logging defined, which log detail record related macros, interfaces, mainly used in VLOG and VLOG_IF and RAW_VLOG like to trigger recording; Declaration Macros VLOG_IS_ON, the current recording mark FLAGS_v less verboselevel TRUE is returned; furthermore SetVLOGLevel : mode setting module specified VLOG (_IS_ON) is log_level level; VModuleInfo internal type list traversal vmodule_list, fuzzy matching to find the specified mode and set the appropriate level module; kLogSiteUninitialized currently only supports the compiler uses __GNUC__; FLAGS_v default initial value is 0, FLAGS_vmodule initial value ""; vmodule_lock lock module, inited_vmodule (flase) whether the module is a list of initialization; 

utilities.h: 
    providing utility functions for internal use, ARRAYSIZE acquisition element size of the container; 
  ProgramInvocationShortName: Get save the program log segment name, the name of one of the sections saved as a log file name of the segment (g_program_invocation_short_name); 
  IsGoogleLoggingInitialized: whether Glog has been initialized, the internal procedures by determining the log segment g_program_invocation_ short_name to determine whether NULL; 
  is_default_thread: whether the default thread, through the inside of g_program_invocation_short_name determines whether or NULL if addition is empty to determine binding g_main_thread_id;
  CycleClock_Now: get the current system time,
  UsecToCycles: The Cycle Timing into the milliseconds (actually inside without any treatment),
  WallTime_Now: Get current system time in microseconds;
  GetMainThreadPid: the main thread acquires the current process the PID (g_main_thread_pid);
  PidHasChanged: determining whether the process ID of the main thread has been changed, Ruoyi change, change it to the main thread of the current process PID;
  gettid: internal get through the current thread ID GetCurrentThreadId;
  MyUserName: get the current user name;
  const_basename: get the file path of the file name;
  sync_val_compare_and_swap: determine the current value and the old value are equal, then the current if the value is set equal to the new value;
  CrashReason: Crash reasons configuration information, comprising an internal file name, line number, and information crash context stack depth;   SetCrashReason: Causes content provided crash;
  InitGoogleLoggingUtilities: initialization function tool glog Related,
  ShutdownGoogleLoggingUtilities: Close glog tool function, the internal initialization setting g_program_invocation_short_name, g_main_thread_id   (in fact two or more interfaces are InitGoogleLogging ShutdownGoogleLogging call); logging.h: Basically save the header file will contain the log records, internal records to achieve a variety of ways are available, unified for different compilers, the variable type declaration under heavy platform and a variety of macros, flow definitions; GOOGLE_STRIP_LOG: Global truncated macro, the compiler will remove Log severity level is below the specified value; this value should be defined macro i.e. before logging.h header
    [log Level, month the GMT, DATE, Time, thread_id, the basename File, line];#define GOOGLE_STRIP_LOG SomeValue; defines various identity, most used to control the output behavior, generally through environment variables, command lines, and can be disposed directly into the log before the log output, an intermediate section identifies the settings may not take effect, it is noted; these identification values are as follows:   logtostderr: output log to stderr, the default is false;   alsologtostderr: log output to stderr, the default is false;   colorlogtostderr: color output log information to the stderr, the default is false; and, depending on the log level to a different color, GLOG_INFO: default color black, GLOG_WARNING: warning yellow, GLOG_ERROR GLOG_FATAL and red (by setting SetConsoleTextAttribute);   stderrthreshol: set the output log limit, i.e., when the output of the identification information is greater than the current value stderr, will be written to stderr; the default value That includes 2 INFO, WARNING ERROR;   log_prefix: log prefix disposed in rows, the default value is 2, the format of the prefix:   logbuflevel: log recording buffer level setting, the default value is 0, when the level is greater than the current value immediately written, otherwise will be buffered to the buffer area, when recording the number of bytes in addition reached 10 ^ 6 bytes will be written to the file;   logbufsecs: buffer record number of seconds is provided, the default value is 30;   minloglevel: setting a minimum level of the log, below this level will not be recorded, the default value is 0;   log_dir: log log save directory, the default is taken from the environment variable GOOGLE_LOG_DIR or TEST_TMPDIR in;   log_link: log file link paths, is not supported under Windows;   v: display m is equal to less than all of the message VLOG can be used - vmodule instead;   max_log_size: set the maximum size of the logging file, MB create new units, the default value 1800, the current exceeds the current size of the remaining data is saved to a file, and the other log files are saved information;   stop_logging_if_full_disk: set when the disk is full, whether to continue to save, the default value is false;   support those who save the macro level records compiled in accordance with the determination of the value of user-defined macros GOOGLE_STRIP_LOG settings, such as: COMPACT_GOOGLE_LOG_INFO, LOG_TO_STRING_INFO;     COMPACT_GOOGLE_LOG_WARNING, LOG_TO_STRING_W ARN ING;     COMPACT_GOOGLE_LOG_ERROR, LOG_TO_STRING_ERROR;     COMPACT_GOOGLE_LOG_FATAL, LOG_TO_STRING_FATAL; user defined macro values provided as necessary;   Further also defines google style LOG macros and SYSLOG macros, such as:     GOOGLE_LOG_INFO, SYSLOG_INFO;     GOOGLE_LOG_WARNING, SY SLOG_WARNING;     GOOGLE_LOG_ERROR, SYSLOG_ERROR;     GOOGLE_LOG_FATAL, SYSLOG_FATAL;     GOOGLE_LOG_DFATAL, SYSLOG_DFATAL;   above macro primary facilitate the user simply use LOG macros and SYSLOG macros defined; inner depending levels invoke different LogMessage of SendMethod;   LOG_SYSRESULT: providing an error code string and written to the log message format (in fact determines whether there is an abnormality inside, for the abnormal calls and written to the log file FormatMessageA);   the lOG, the SYSLOG macro: ease of use of the macro user use a similar way lOG (INFO), SYSLOG (ERROR)   InitGoogleLogging / ShutdownGoogleLogging: initializing the library and the library is closed, inside the main part of the initialization parameters and resources (in fact, for the release of log_destinations_ log destination array of objects and logging_directories_list log directory listing application release );   InstallFailureFunction: triggers function calls mounted) installation function calls (calling LOG (FATAL) for failure;   LOG_TO_SINK, LOG_TO_SINK_BUT_NOT_TO_LOGFILE: save the message information to the slot, Saved in the specified message to a specified channel and message information extracted; the former calls SendToSinkAndLog saved and output to the log, which is only the message information stored, in addition slink if the parameter is NULL, it will not be printed out directly saved log;   LOG_TO_STRING: save the message information to the string, if the parameter is NULL, directly outputs the print log;   LOG_STRING: save the message information to the Vector < string > , if the parameter is NULL, directly outputs the print log;   LOG_IF /SYSLOG_IF: Condition log macro, inside the conditional call LOG (Severity), SYSLOG (Severity);   LOG_ASSERT / SYSLOG_ASSERT: assert macro, called internally conditional macro (whose parameters FATAL);   CHECK: conditions to detect macro will stop the test fails, internal call conditional macro ( its parameters FATAL);   CheckOpString: detecting option character string, character string data is often used as a container;   GetReferenceableValue: overloaded version number value acquired by reference internal function sets;   DummyClassToDefineOperator: empty class, is for implementing overload std :: the ostream & operator << (STD :: the ostream & OUT , ...); this facilitates the user to achieve their class to implement the macro detection CHECK conditions, but the user should be achieved & STD :: the ostream operator << (STD :: the ostream & OUT , ...);   MakeCheckOpValueString: overloaded version to effect a series of operator << operation;   CheckOpMessageBuilder: message builder auxiliary MakeCheckOpString, generating a message formatted information;   DEFINE_CHECK_OP_IMPL / CHECK_OP_LOG /CHECK_OP: The main helper macros CHECK_XXX achieve test macro and debug macros DCHECK;   the VLOG, DLOG: debugging macros and detailed log of the macro;   the following for important structures for internal use and the type of analysis:   LogStreamBuf: log stream buffer class, with a buffer function, inherited from std :: streambuf, the main achievement of the last two filtering "\ n" characters; LogStreamBuf Further and as referenced object class LogStream log stream;   LogStream: log stream class inherits std :: ostream, as the log data output stream is LogMessage internal class information such as log; NullStream air flow in addition to LogStream class is derived, is its main significance GOOGLE_STRIP_LOG macro user defined value, to compile the class empty support streaming operations, to support operator << operation only;   LogMessage: log informational, basically such a complete interface majority of log information related operations, achieve; many macro ( : LOG ()) inside the class will create an object and initialize the class, implement the log information to maintain, print and other operations; in addition LogMessageFatal fatal error message classes and ErrnoLogMessage message classes (used in PLOG related macro) are inherited in LogMessage;   LogMessageData: log message data class, the main internal error code stored message content (which can accommodate up to kMaxLogMessageLen ( 30000 ) bytes of information), severity, log stream, row, the file path name and file name, send_method_ destructor call, message time stamp, length information; LogMessage as a reference object;   the Lo gDestination: log destination class, the main flow of information to implement the log data; glog currently present as singleton (actually an array comprising four elements) are GLOG_INFO, GLOG_WARNING, GLOG_ERROR, GLOG_FATAL; providing a plurality of internal operations static member function; log data currently provides information to stderr, email, logfile, sink; use different objects and purposes of the log different log data flows for different macros;   Logger: log write, primarily responsible for maintaining written to the log, the time stamp, the buffer, the formatting operation;   LogFileObject: log file writer, responsible for writing the file-related operations, inherited from Logger; and as LogDestination log destination members of the object class; LogDestination to assist in the operation log file;   LogSink: log slot class inherit from this class and implement a user interface to send, to enable a user operation log information, is also present as a separate class; and finally re-analysis LogMessage log information classes: class overrides a plurality of versions of the constructors, to support the log information to the character string string, Vector < string > container, LogSink groove, log information detection, in addition to log statistics, acquiring current data streams, etc. ; important global or static variable: kMaxLogMessageLen: maximum log size, in bytes, the default value is 30,000 bytes; log_destinations_: log destination array object class; log_mutex: global lock, only one thread at a time only the operation log data ; num_messages_: message count array, divided Save the current number of messages corresponding to severity level; stop_writing: Global disable write operation, generally used in the disk is full and can not write time; LogSeverityNames: an array of string name severity level; email_logging_severity_: the email severity level ( 99999 ); addresses_: receiving email address; hostname_: send the current hostname of the email; sinks_: Global log tank vector vessel, traverses the tank container in log destination class object call; sink_mutex_: global log slot lock slot to protect resources; terminal_supports_color_: console output terminal supports color output; fatal_msg_lock: fatal messages lock; to protection under the multi-thread calls LOG (fATAL) data, mainly for the protection of LogMessageData type of fatal_msg_data_exclusive and fatal_msg_data_shared these two deadly message data, the strategy adopted for the first time in the first thread fatal message using fatal_msg_data_exclusive, after the thread is used fatal_msg_data_shared; crash_reason: crash reasons, mainly used in the first fatal crash cause and obtain interchanged with g_reason equality; fatal_msg_exclusive: fatal exclusive message identification for switching fatal_msg_data_exclusive and fatal_msg_data_shared; fatal_time: stamp when the fatal message to occur; STD :: the streambuf A LogStreamBuf A ' fatal_message: message content when a fatal message to occur; logging_directories_list: log directory listing; the log to identify a list of contents actually create FLAGS_log_dir; class diagram: the ostream B :: STD LogStream B ' NullStream B' ' LogStreamBuf A * LogMessage C ErrnologMessage C' LogMessageFatal C '' LogMessageData D LogStream B ' + Logger E LogFileObject E' LogDestionation F. Logger E * LogSink G description: inheritance hierarchy relationship with * as a reference, + band comprising; in fact, the class diagram for the relationship, substantially divided into three parts, message processing, message distribution, message storage; raw_logging.h: Original logging, you can use the macro RAW_LOG, RAW_VLOG, RAW_DLOG, RAW_CHECK, RAW_DCHECK such as macros, which thread-safe handle that is used internally a message stack to ensure that multi-thread-safe; RAW_LOG: internal macro call with the parameter determining the appropriate severity level the RAW_LOG_INFO, RAW_LOG_WARNING, RAW_LOG_ERROR, RAW_LOG_FATAL macros (the fact that these are implemented in accordance with the value red macro call RawLog__ truncated or RawLogStub__); STRIP_LOG: macro truncation, thin to achieve the raw log by macro;   RAW_VLOG: the conditional macro macro cutoff value , call the appropriate macro RAW_LOG_INFO or RawLogStub__;   RawLogStub__: raw log pile, air operations;   RAW_CHECK: test macro, internal call RAW_LOG (FATAL, ...);   RAW_DLOG / RAW_DCHECK: debugging macros (calling RAW_LOG), debugging test macro (call RAW_CHECK) ; again using macros:   RawLog__: function call in RAW_LOG and RAW_VLOG macros, the original log record formatting and other operations;   RawLog__SetLastTime: set to save the last of the original logging system time;   the necessary static or global variables:     kLogBufSiz e: the maximum length of the original log record ( 3000 );     crashed: whether Crash;     crash_reason: Cause Crash;   crash_buf: Crash buffer (kLogBufSize size); stl_logging.h: Support Standard Template Library STL is output to the stream object, using the examples: List < String > X; the LOG (the INFO) << " Data: " << X; Vector < int > V1, V2; CHECK_EQ (V1, V2); PrintSequence: template functions, sequence to a stream object, up to 100 printing elements separated by a space, for the remaining elements to "..." end; reload multiple versions :: ostream std & operator << (std :: ostream & OUT , ...); STL container object at the time to support different parameters corresponding to the internal call PrintSequence as the actual printing operation; furthermore declares OUTPUT_TWO_ARG_CONTAINER, OUTPUT_THREE_ARG_CONTAINER, OUTPUT_FOUR_ARG_CONTAINER macros are used to support the Vector :: std, std :: deque, std :: List; std :: the SET , std :: multiset; std :: the Map, std ::multimap; there is also a special version :: ostream std & operator<< (std :: ostream & OUT , const std :: pair <First, Second> & the p-) to support std :: pair; Most macros are created LogMessage object instance and call the appropriate constructor to initialize and according to severity interfaces, data processing in addition to the final result of this example is a partial object will be destructed, call the appropriate function output processing when the destructor; only as part of the macro test determination condition; may additionally also perform some basic prior InitGoogleLogging testing, logging; print log format: when the level of the first day of a character: minutes: seconds microseconds thread ID file name: row] information log file name to save the format: an executable application name computer name user name. .log level date. - when every minute process ID. log file contents are saved format: file header example: the log file the Created AT: 2015 / 12 / 23 09 : 38 : 12 Running Machine ON: haomiao Log line format: [IWEF] mmdd hh: mm: ss.uuuuuu threadid file: line] msg file content: log with the print format; when substantially generate a log file for each level, when it reaches the maximum file size will be re the new generation of the corresponding level of the log file to save a log; project summary: overall GLog open source logging library is not complicated, it provides a number of flow operations and macro assistants, support to the console output, file output, email sending output, Sink (user custom control output operation), the user actually can use custom implementation Sink network output socket, or other means; severity of a variety of flexible log log output and control settings identifier; addition and accidental conditions, debugging, inspection, logging details macro raw logging data to the stream supports STL containers;
  in addition to a portion of the internal static variables stored as data for other data exchange, to reduce the overhead and memory allocation may be fragmented, and reasonable control of the output information to a file; however, do not support the control and network behavior log output from the configuration file, not Support unicode, does not support custom log file name and save any log files generated, relative Log4plus and other open source logging library, so it was not very flexible;

Guess you like

Origin www.cnblogs.com/haomiao/p/11647340.html