kk Blog —— 通用基础


date [-d @int|str] [+%s|"+%F %T"]
netstat -ltunp
sar -n DEV 1

nignx log_format 日志时间格式

https://bnxb.com/nginx/27544.html

Nginx的默认访问日志的时间格式是:[08/Mar/2018:10:30:58 +0800],由日志参数中的$time_local变量表示。

改成常用格式:2018-06-08 10:11:23

有两种方法,一种是修改源码,然后编译,一种是外挂lua来实现

一、lua 方法

不修改 nginx 源代码的,具体如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
http {
	log_format  main  '$fmt_localtime $request_time $server_addr $server_port $remote_addr $remote_port $status $body_bytes_sent $request_method $server_protocol'
			  ' "$host" "$uri" "$query_string" "$http_referer" "$http_user_agent" "$http_x_forwarded_for" - $remote_user';

	access_log  /var/log/nginx/access.log  main;

	map $host $fmt_localtime {
		default '';
	}
	log_by_lua_block {
		ngx.var.fmt_localtime = ngx.localtime();
	}
	...
}

代码的解释如下:

首先我们自定义一个nginx 变量 $fmt_localtime , 因为在http context不能够使用 set $variable。

所以我们采用map的方式如下

1
2
3
map $host $fmt_localtime {
	default '';
}

2) 然后我们用 log_by_lua_block 设置 ngx.fmt_localtime 的时间

3) 设置日志格式 log_format使用 $fmt_localtime 作为时间参数

二、修改nginx源代码

需要修改的文件

src/core/nginx_times.c

src/http/modules/ngx_http_log_module.c

首先修改ngx_http_log_module.c文件:

1
ngx_string("time_iso8601"), sizeof("1970-09-28T12:00:00+06:00") - 1,

更改后

1
ngx_string("time_iso8601"), sizeof("1970-09-28 12:00:00") - 1,

然后修改nginx_times.c文件:

1
[sizeof("1970-09-28T12:00:00+06:00")];

更改后

1
[sizeof("1970-09-28 12:00:00")];
1
ngx_cached_http_log_iso8601.len = sizeof("1970-09-28T12:00:00+06:00") - 1;

更改为

1
ngx_cached_http_log_iso8601.len = sizeof("1970-09-28 12:00:00") - 1;
1
2
3
4
5
6
(void) ngx_sprintf(p3, "%4d-%02d-%02dT%02d:%02d:%02d%c%02d:%02d",
		tm.ngx_tm_year, tm.ngx_tm_mon,
		tm.ngx_tm_mday, tm.ngx_tm_hour,
		tm.ngx_tm_min, tm.ngx_tm_sec,
		tp->gmtoff < 0 ? '-' : '+',
		ngx_abs(tp->gmtoff / 60), ngx_abs(tp->gmtoff % 60));

更改为

1
2
3
4
(void) ngx_sprintf(p3, "%4d-%02d-%02d %02d:%02d:%02d",
		tm.ngx_tm_year, tm.ngx_tm_mon,
		tm.ngx_tm_mday, tm.ngx_tm_hour,
		tm.ngx_tm_min, tm.ngx_tm_sec);

最后重新编译,并使用新的时间变量

将 nginx 配置文件中的 $time_local 改为 $time_iso8601 即可。