日志

作者: Lisa_Guo | 来源:发表于2020-01-17 09:52 被阅读0次

    Nginx的日志分两种:错误日志(error log)、访问日志(access log),一般存放在nginx安装目录下logs目录里,默认分别为“error.log“、“access.log”
    错误日志 记录网络发生异常错误时的信息,方便发生错误时对问题进行追踪,访问日志 则记录所有对服务的访问信息,可对用户的浏览行为进行追踪

    访问日志

    nginx的访问日志主要有以下2个参数控制

    • log_format:
      用来定义记录日志的格式(可以定义多种日志格式,取不同的名字即可)
    • access_log:
      用来指定日志文件的路径及使用何种日志格式记录日志

    日志格式

    日志格式 log_format 语法如下

    log_format name [escape=default|json|none] string ...;
    
    // default value
    log_format  combined '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
    

    name: 为日志格式命名,可定义多个日志格式
    string: 具体格式
    escape: none 对字符不转义,json|default则对字符进行转义

    部分可用字段

    字段名 描述
    $remote_addr 记录访问网站的客户端地址;
    $http_x_forwarded_for 当前端有代理服务器时,设置web节点记录客户端地址的配置,此参数生效的前提是代理服务器上也进行了相关的x_forwarded_for设置;
    $remote_user 远程客户端用户名称;
    $time_local 记录访问时间与时区;
    $request 用户的http请求起始行信息;
    $status http状态码,记录请求返回的状态,例如200、404、301等;
    $body_bytes_sent 服务器发给客户端的响应body字节数;
    $http_referer 记录此次请求是从哪个链接访问呢过来的,可以根据referer进行防盗链设置;
    $http_user_agent 记录客户端访问信息,例如:浏览器、手机客户端等;

    存放位置: http

    日志文件

    定义日志文件语法如下

    access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]];
    
    access_log  off
    
    // default value
    access_log logs/access.log combined;
    

    path: 存放路径, 默认为logs/access.log
    format: 日志格式,默认为combine
    buffer=size: 存放日志的缓冲区大小
    flush=time: 为将缓冲区的日志刷到磁盘的时间
    gzip[=level] : 表示压缩级别
    [if=condition] : 表示其他条件,一般场景这些参数都无需配置,极端优化时才可能考虑这些参数。

    放置位置:http, server, location, if in location, limit_except中

    实例

    以下示例定义了两个日志格式main,json,定义默认的日志路径logs/access.log, 并在8080端口的server中自定义日志文件。

    [root@nginx conf]# cat nginx.conf
    worker_processes  1;
    error_log   logs/error.log  error;
    events {
        worker_connections  1024;
    }
    http {
        include       mime.types;
        default_type  application/octet-stream;
        log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                          '$status $body_bytes_sent "$http_referer" '
                          '"$http_user_agent" "$http_x_forwarded_for"';
       log_format  json '{ address: $remote_addr }';
    
       access_log logs/access.log main;  // 默认日志文件
     
        sendfile        on;
        keepalive_timeout  65;
    
       server {
           listen 8080;
           access_log  /data/project/logs/report.log json;  // 自定义日志文件
           root /data/project;
       }
    }
    

    参考文章
    https://www.cnblogs.com/Mr-Ding/p/9539867.html
    http://www.madblog.cn/posts/e4dd5bbae50fa621.html

    相关文章

      网友评论

          本文标题:日志

          本文链接:https://www.haomeiwen.com/subject/xrnfzctx.html