如何根据文件文件大小旋转窗口的nginx日志

时间:2017-06-29 06:50:15

标签: nginx server

我无法在nginx中配置日志轮换。 我已经使用Windows服务包装器在Windows机器上安装了nginx服务。 我尝试使用nginx -s reopen重新打开日志文件但命令给我错误。

2 个答案:

答案 0 :(得分:0)

尝试以下链接 Nginx loggging tips

答案 1 :(得分:0)

Nginx在Windows或任何其他平台上没有任何用于滚动日志的内置模块,如果您使用nginx.exe运行nginx,则可以重新打开nginx日志但是如果您使用已安装的服务运行nginx,则必须停止服务然后旋转日志,然后再次启动服务,

使用下面的批处理脚本来旋转nginx错误日志并访问Windows机器上的日志

REM script to rotates nginx logs from java/windows cmd prompt

REM rolloverNginxLogs.bat [maxFileSize in bytes] [retainCount]
REM e.g rolloverNginxLogs.bat 10000 5

@echo off
setlocal EnableDelayedExpansion
pushd C:\nginx\logs

set ERRORLEVEL=0
set maxFileSize=%1
set retainCount=%2
set errorLogFile=error.log
set accessLogFile=access.log

set rotateAccessLogFile=""
set rotateErrorLogFile=""
set rotateFile=""

REM set current time, replace " " with "0" for hours less than 10
set currentTime=%time:~0,2%%time:~3,2%%time:~6,2%
if %currentTime% LSS 100000 (set currentTime=%currentTime: =0%)

REM check if access.log file rotation required
for %%A in (%accessLogFile%) do (
    echo.Size of "%%A" is %%~zA bytes
    if /I %%~zA GTR %maxFileSize% (
        set rotateAccessLogFile=true
        set rotateFile=true
    )
)

REM check if error.log file rotation required
for %%A in (%errorLogFile%) do (
    echo.Size of "%%A" is %%~zA bytes
    if /I %%~zA GTR %maxFileSize% (
        set rotateErrorLogFile=true
        set rotateFile=true
    )
)

REM if required rotate logs otherwise exit
if "%rotateFile%" EQU "true" (
    goto ROTATELOG
) else (
    goto DONE
)

:ROTATELOG 
REM check whether the service is running if running then stop service
for /F "tokens=3 delims=: " %%H in ('sc query "nginx" ^| findstr "STATE"') do (
  if /I "%%H" EQU "RUNNING" (
   net stop "nginx"      
  )
)

REM rotate error log
if "%rotateErrorLogFile%" EQU "true" (
    ren error.log error-%DATE%-%currentTime%.log
    for /f "skip=%retainCount% eol=: delims=" %%F in ('dir /b /o-d /a-d error*.log') do @del "%%F"
)

REM rotate access log
if "%rotateAccessLogFile%" EQU "true" (
    ren access.log access-%DATE%-%currentTime%.log
    for /f "skip=%retainCount% eol=: delims=" %%F in ('dir /b /o-d /a-d access*.log') do @del "%%F"
)

REM check if the service is not running, start service
for /F "tokens=3 delims=: " %%H in ('sc query "nginx" ^| findstr "STATE"') do (
  if /I "%%H" NEQ "RUNNING" (

   echo starting nginx service
   net start "nginx"   
  )
)

:DONE
popd
exit %ERRORLEVEL%