Nginx日志格式定义

avatar 2019年11月8日19:57:24 评论 1,198 次浏览

Nginx日志格式默认是main,也就是生成的access.log文件中的格式内容,如果想根据自己的要求打印出相应的格式以便在统计的时候能够更方便的分析日志内容,就需要自己定义日志格式了。不过在access.log文件中生存的是接口的URL,如果nginx下面有代理服务器,也可以根据access.log文件来健康接口的状态。下面我们根据自己的方式来修改nginx日志格式:

access.log使用的是nginx的main,下面使用log_format,具体可设置的参数以及说明如下:

参数 说明 实例
$remote_addr 客户端地址 114.114.114.114
$remote_user 客户端用户名称 --
$time_local 访问时间和时区 18/Jul/2019:17:00:01 +0800
$request 请求的URI和HTTP协议 GET / HTTP/1.1
$http_host 请求地址 www.wulaoer.org
$status HTTP请求状态 200
$upstream_status upstream状态 200
$body_bytes_sent 发送给客户端文件内容大小 13200
$http_referer url跳转来源 https://www.baidu.com/
$http_user_agent 用户终端浏览器等信息 "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; SV1; GTB7.0; .NET4.0C;
$ssl_protocol SSL协议版本 TLSv1
$ssl_cipher 交换数据中的算法 RC4-SHA
$upstream_addr 后台upstream的地址,即真正提供服务的主机地址 10.10.10.100:80
$request_time 整个请求的总时间 0.205
$upstream_response_time 请求过程中,upstream响应时间 0.002

下面我使用我自己的环境做一下:

在nginx.conf的http中增加:

    log_format logstash_json '{ "visit_time": "$time_iso8601", '
        '"remote_addr": "$remote_addr", '
        '"remote_user": "$remote_user", '
        '"body_bytes_sent": $body_bytes_sent, '
        '"request_time": $request_time, '
        '"status": "$status", '
        '"request": "$request", '
        '"request_body": "$request_body", '
        '"request_method": "$request_method", '
        '"http_referrer": "$http_referer", '
        '"cookie_uuid": "$cookie_uuid_var", '
        '"original_cookie_uuid": "$cookie_uuid", '
        '"neo_id": "$http_x_nhn_user_id_no", '
        '"neo_user_id": "$http_x_nhn_user_id", '
        '"neo_svc_cd": "$http_x_nhn_svc_cd", '
        '"neo_sns_id": "$http_x_nhn_sns_id", '
        '"neo_sns_cd": "$http_x_nhn_sns_cd", '
        '"http_user_agent": "$http_user_agent" } ';

并把日志输出的格式修改一下默认是main

access_log  /home/wwwlogs/access.log;       #这是系统默认的日志格式
access_log   /home/wwwlogs/access_json.log logstash_json;  #自定义的日志格式

重新加载一个nginx,让配置文件生效

/etc/init.d/nginx reload

查看一下日志输出路径下的文件格式:

[root@wulaoer wwwlogs]# ls 
access-20190923.log  access-20190929.log  access_json.log  access.log  nginx_error.log  nginx.pid

nginx日志格式已经修改完成,后面就是对日志格式进行分割,可以使用工具也可以自己写脚本,下面看一下我的简单些的脚本:

#!/bin/bash
logspath=/home/wwwlogs/
logdate=`date +%Y%m%d`
cd $logspath
mv access.log access-$logdate.log
mv access_json.log access_json-$logdate.log
/etc/init.d/nginx reload

定时任务区执行这个脚本就可以了。

avatar

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: