很多系统,都需要标准化输出Log,达到直观阅读Log的目的。
这个是在Linux上测试的,如果需要移植到其他的系统,请根据系统情况实现inner_中的系统相关函数。
自己实现了一个Log输出实现,可以根据自己需要自定义输出格式。完整输出如android的规范输出:
05-16 15:21:18.501 11942 11942 F main:pid:100,tid:200
05-16 15:21:18.501 11942 11942 E main:pid:100,tid:200
05-16 15:21:18.501 11942 11942 W main:pid:100,tid:200
05-16 15:21:18.501 11942 11942 I main:pid:100,tid:200
05-16 15:21:18.501 11942 11942 D main:pid:100,tid:200
05-16 15:21:18.501 11942 11942 V main:pid:100,tid:200
输出格式:
05-16:日期
15:21:18.501:具体的时间 ,精确到ms
11942:进程ID
11942:线程ID
F/E/W/I/D/V:打印级别
main:TAG
pid:100,tid:200:具体的打印内容
测试代码如下:
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include "Logger.h"
int main()
{
LOGF("main","pid:%d,tid:%d",100,200);
LOGE("main","pid:%d,tid:%d",100,200);
LOGW("main","pid:%d,tid:%d",100,200);
LOGI("main","pid:%d,tid:%d",100,200);
LOGD("main","pid:%d,tid:%d",100,200);
LOGV("main","pid:%d,tid:%d",100,200);
return 0;
}
实现如下:
logger.h
#ifndef __LOGGER_H__
#define __LOGGER_H__
#include <stdarg.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* Declare maximum logging level/verbosity. Lower number indicates higher
* importance, with the highest importance has level zero. The least
* important level is five in this implementation, but this can be extended
* by supplying the appropriate implementation.
*
* The level conventions:
* - 0: fatal error
* - 1: error
* - 2: warning
* - 3: info
* - 4: debug
* - 5: verbosity
*
* Default: 4
*/
#ifndef LOGGER_MAX_LEVEL
#define LOGGER_MAX_LEVEL 5
#endif
/**
* Log decoration flag, to be specified with #tk_log_set_decor().
*/
enum log_decoration
{
LOG_HAS_YEAR = 1, /**< Include year digit [no] */
LOG_HAS_DAY = 2, /**< Include day of month [no] */
LOG_HAS_TIME = 4, /**< Include time [yes] */
LOG_HAS_SENDER = 8, /**< Include sender in the log [yes] */
LOG_HAS_COLOR = 16, /**< Colorize logs [yes on win32] */
LOG_HAS_LEVEL_TEXT = 32, /**< Include level text string [no] */
LOG_HAS_THREAD_ID = 64, /**< Include thread identification [no] */
LOG_HAS_THREAD_SWC = 128, /**< Add mark when thread has switched [yes]*/
LOG_HAS_CR = 256, /**< Include carriage return [no] */
LOG_HAS_NEWLINE = 512 /**< Terminate each call with newline [yes] */
};
/**
* Signature for function to be registered to the logging subsystem to
* write the actual log message to some output device.
*
* @param level Log level.
* @param data Log message, which will be NULL terminated.
* @param len Message length.
*/
typedef void logger_func(int level, const char *data, int len);
vo