syslog,可以保存应用日志到本地,也可以透过tcp或udp传送到远端syslog服务器
openwrt 19.07
- 添加系统配置,指定log文件:option log_file ‘/var/log/message.log’,指定log大小:option log_size ‘64’
root@Eric:/# cat /etc/config/system
config system
option hostname 'Eric'
option timezone 'UTC'
option ttylogin '0'
option log_size '64'
option log_file '/var/log/message.log'
option urandom_seed '0'
- 在代码中修改,package/base-files/files/bin/config_generate 中添加 set system.@system[-1].log_file=’/var/log/message.log’
generate_static_system() {
# eric++
# set system.@system[-1].hostname='OpenWrt'
# set system.@system[-1].log_file='/temp/log/message.log'
# set system.@system[-1].conloglevel='5'
uci -q batch <<-EOF
delete system.@system[0]
add system system
set system.@system[-1].hostname='Eric'
set system.@system[-1].timezone='UTC'
set system.@system[-1].ttylogin='0'
set system.@system[-1].log_size='64'
set system.@system[-1].log_file='/var/log/message.log'
set system.@system[-1].urandom_seed='0'
delete system.ntp
set system.ntp='timeserver'
set system.ntp.enabled='1'
set system.ntp.enable_server='0'
add_list system.ntp.server='0.openwrt.pool.ntp.org'
add_list system.ntp.server='1.openwrt.pool.ntp.org'
add_list system.ntp.server='2.openwrt.pool.ntp.org'
add_list system.ntp.server='3.openwrt.pool.ntp.org'
EOF
- 程序中调用syslog,重定义log为全局调试接口
#include <syslog.h>
// #define DEBUG
#ifdef DEBUG
#define log(fmt, args...) \
printf("[%s](%d)" fmt , __func__, __LINE__, ## args)
#define logerr log
#define loginfo log
#else
#define log(fmt, args...) \
syslog(LOG_NOTICE|LOG_USER,"[%s](%d)" fmt , __func__, __LINE__, ## args)
#define logerr(fmt, args...) \
syslog(LOG_ERR|LOG_USER,"[%s](%d)" fmt , __func__, __LINE__, ## args)
#define loginfo(fmt, args...) \
syslog(LOG_INFO|LOG_USER,"[%s](%d)" fmt , __func__, __LINE__, ## args)
#endif
- 其中,%m 被代换成对应 errno 错误消息字串(strerror)
syslog(LOG_ERR|LOG_USER,"%m\n");
- 测试:
while (1) {
sleep(2);
log("cnt=%d\n",cnt++);
}
- 使用logread -f 实时查询程序输出的log
root@Eric:/# logread -f
Sun Sep 6 17:14:23 2020 user.notice : [main](33)cnt=420
Sun Sep 6 17:14:25 2020 user.notice : [main](33)cnt=421
Sun Sep 6 17:14:27 2020 user.notice : [main](33)cnt=422
Sun Sep 6 17:14:29 2020 user.notice : [main](33)cnt=423
Sun Sep 6 17:14:31 2020 user.notice : [main](33)cnt=424