search
HomeOperation and MaintenanceNginxHow to set the access_log log of nginx

How to set the access_log log of nginx

May 31, 2023 am 10:28 AM
nginxaccess_log

nginx 日志主要有两条指令:1)log_format:用来设置日志格式;2)access_log:用来指定日志文件的存放路径、格式

How to set the access_log log of nginx

log_format 日志格式

1、语法:

log_format name(格式名字) 格式样式(即想要得到什么样的日志内容) 示例:

log_format main'$remote_addr - $remote_user [$time_local] "$request" ''$status $body_bytes_s ent "$http_referer" ''"$http_user_agent" "$http_x_forwarded_for"'
2、具体参数格式
How to set the access_log log of nginx
3、x_forwarded_for:

通常web服务器放在反向代理的后面,这样就不能获取到客户的IP地址了,通过$remote_addr拿到的IP地址是反向代理服务器的iP地址。反向代理服务器在转发请求的http头信息中,可以增加x_forwarded_for信息,用以记录原有客户端的IP地址和原来客户端的请求的服务器地址。

:在server中设置x_forwarded_for

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

access_log

用了log_format 指令设置了日志格式之后,需要用access_log指令指定日志文件的存放路径;

1、语法:

access_log path(存放路径) format (自定义日志名称) 示例:

access_log logs/access.log main;
2、设置刷盘策略:
access_log /data/logs/nginx-access.log buffer=32k flush=5s;

buffer 满 32k 才刷盘;假如 buffer 不满 5s 钟强制刷盘。

:一般log_format在全局设置,可以设置多个。access_log 可以在全局设置,但往往是定义在虚拟主机(server)中的location中。 例如:

http {
log_format main '$remote_addr - $remote_user [$time_local] "$request" ''"$status" $body_bytes_sent "$http_referer" ''"$http_user_agent" "$http_x_forwarded_for" ''"$gzip_ratio" $request_time $bytes_sent $request_length';
log_format srcache_log '$remote_addr - $remote_user [$time_local] "$request" ''"$status" $body_bytes_sent $request_time $bytes_sent $request_length ''[$upstream_response_time] [$srcache_fetch_status] [$srcache_store_status] [$srcache_expire]';
open_log_file_cache max=1000 inactive=60s;
server {
server_name ~^(www\.)?(.+)$;
access_log logs/$2-access.log main;
error_log logs/$2-error.log;
location /srcache {
access_log logs/access-srcache.log srcache_log;
}
}
}
3、其他:

1)error_log:

配置错误日志,例如上例。

2)open_log_file_cache:

对于每一条日志记录,都将是先打开文件,再写入日志,然后关闭。你可以使用open_log_file_cache来开启日志文件缓存(默认情况下是关闭的)。 语法:

open_log_file_cache max=N [inactive=time] [min_uses=N] [valid=time];

参数注释如下:

  • max:设置缓存中的最大文件描述符数量,如果缓存被占满,采用LRU算法将描述符关闭。

  • inactive:设置存活时间,默认是10s

  • min_uses:设置在inactive时间段内,日志文件最少使用多少次后,该日志文件描述符记入缓存中,默认是1次

  • valid:设置检查频率,默认60s

open_log_file_cache max=1000 inactive=20s valid=1m min_uses=2;

3)日志分析:

通过对日志格式的定义,就可以使用常见的 Linux 命令行工具进行分析了:

查找访问频率最高的 URL 和次数:

cat access.log | awk -F ‘^A’ ‘{print $10}’ | sort | uniq -c

查找当前日志文件 500 错误的访问:

cat access.log | awk -F ‘^A’ ‘{if($5 == 500) print $0}’

查找当前日志文件 500 错误的数量: cat access.log | awk -F ‘^A’ ‘{if(0}’ | wc -l

查找某一分钟内 500 错误访问的数量:

cat access.log | awk -F ‘^A’ ‘{if($5 == 500) print $0}’ | grep ’09:00’ | wc-l

查找耗时超过 1s 的慢请求:

tail -f access.log | awk -F ‘^A’ ‘{if($6>1) print $0}’

假如只想查看某些位:

tail -f access.log | awk -F ‘^A’ ‘{if($6>1) print $3″|”$4}’

查找 502 错误最多的 URL:

cat access.log | awk -F ‘^A’ ‘{if($5==502) print $11}’ | sort | uniq -c

查找 200 空白页

cat access.log | awk -F ‘^A’ ‘{if($5==200 && $8 print $3″|”$4″|”$11″|”$6}’

切割日志

Nginx 的日志都是写在一个文件当中的,不会自动地进行切割,如果访问量很大的话,将导致日志文件容量非常大,不便于管理和造成Nginx 日志写入效率低下等问题。因此,通常需要对access_log和error_log日志进行分割。 切割日志一般利用USR1信号让nginx产生新的日志。实例:

#!/bin/bashlogdir="/data/logs/nginx"pid=`cat $logdir/nginx.pid`
DATE=`date -d "1 hours ago" +%Y%m%d%H`
DATE_OLD=`date -d "7 days ago" +%Y%m%d`for i in `ls $logdir/*access.log`; domv $i $i.$DATEdonefor i in `ls $logdir/*error.log`; domv $i $i.$DATEdonekill -s USR1 $pidrm -v $logdir"/access.log."$DATE_OLD*rm -v $logdir"/error.log."$DATE_OLD*
1、分析:
  • 将上面的脚本放到crontab中,每小时执行一次(0 ),这样每小时会把当前日志重命名成一个新文件;然后发送USR1这个信号让Nginx 重新生成一个新的日志。(相当于备份日志)

  • 将前7天的日志删除;

2、说明:

在没有执行kill -USR1 $pid之前,即便已经对文件执行了mv命令而改变了文件名称,nginx还是会向新命名的文件”*access.log.2016032623”照常写入日志数据的。原因在于:linux系统中,内核是根据文件描述符来找文件的。

3、logrotates:

使用系统自带的logrotates,也可以实现nginx的日志分割,查看其bash源码,发现也是发送USR1这个信号。

The above is the detailed content of How to set the access_log log of nginx. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Choosing Between NGINX and Apache: The Right Fit for Your NeedsChoosing Between NGINX and Apache: The Right Fit for Your NeedsApr 15, 2025 am 12:04 AM

NGINX and Apache have their own advantages and disadvantages and are suitable for different scenarios. 1.NGINX is suitable for high concurrency and low resource consumption scenarios. 2. Apache is suitable for scenarios where complex configurations and rich modules are required. By comparing their core features, performance differences, and best practices, you can help you choose the server software that best suits your needs.

How to start nginxHow to start nginxApr 14, 2025 pm 01:06 PM

Question: How to start Nginx? Answer: Install Nginx Startup Nginx Verification Nginx Is Nginx Started Explore other startup options Automatically start Nginx

How to check whether nginx is startedHow to check whether nginx is startedApr 14, 2025 pm 01:03 PM

How to confirm whether Nginx is started: 1. Use the command line: systemctl status nginx (Linux/Unix), netstat -ano | findstr 80 (Windows); 2. Check whether port 80 is open; 3. Check the Nginx startup message in the system log; 4. Use third-party tools, such as Nagios, Zabbix, and Icinga.

How to close nginxHow to close nginxApr 14, 2025 pm 01:00 PM

To shut down the Nginx service, follow these steps: Determine the installation type: Red Hat/CentOS (systemctl status nginx) or Debian/Ubuntu (service nginx status) Stop the service: Red Hat/CentOS (systemctl stop nginx) or Debian/Ubuntu (service nginx stop) Disable automatic startup (optional): Red Hat/CentOS (systemctl disabled nginx) or Debian/Ubuntu (syst

How to configure nginx in WindowsHow to configure nginx in WindowsApr 14, 2025 pm 12:57 PM

How to configure Nginx in Windows? Install Nginx and create a virtual host configuration. Modify the main configuration file and include the virtual host configuration. Start or reload Nginx. Test the configuration and view the website. Selectively enable SSL and configure SSL certificates. Selectively set the firewall to allow port 80 and 443 traffic.

How to solve nginx403 errorHow to solve nginx403 errorApr 14, 2025 pm 12:54 PM

The server does not have permission to access the requested resource, resulting in a nginx 403 error. Solutions include: Check file permissions. Check the .htaccess configuration. Check nginx configuration. Configure SELinux permissions. Check the firewall rules. Troubleshoot other causes such as browser problems, server failures, or other possible errors.

How to start nginx in LinuxHow to start nginx in LinuxApr 14, 2025 pm 12:51 PM

Steps to start Nginx in Linux: Check whether Nginx is installed. Use systemctl start nginx to start the Nginx service. Use systemctl enable nginx to enable automatic startup of Nginx at system startup. Use systemctl status nginx to verify that the startup is successful. Visit http://localhost in a web browser to view the default welcome page.

How to check whether nginx is started?How to check whether nginx is started?Apr 14, 2025 pm 12:48 PM

In Linux, use the following command to check whether Nginx is started: systemctl status nginx judges based on the command output: If "Active: active (running)" is displayed, Nginx is started. If "Active: inactive (dead)" is displayed, Nginx is stopped.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.