Last active
December 15, 2023 08:23
-
-
Save jiaming0708/3e8cb7252f350ccdaeb595984595acd9 to your computer and use it in GitHub Desktop.
nginx logrotate on windows
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# nginx folder | |
$nginxFolder = "D:\nginx\logs" | |
# keep log count | |
$keepLogCount = 7 | |
# Maximum log file size in megabytes | |
$maxLogFileSizeMB = 10 | |
# date format | |
$dateFormat = Get-Date -Format "yyyyMMdd" | |
# Define log types | |
$logTypes = @("access", "error") | |
foreach ($logType in $logTypes) { | |
# define backup file name | |
$backupBaseName = "$logType.log.$dateFormat" | |
# get today's backup count in folder | |
$logCount = (Get-ChildItem -Path $nginxFolder -Filter "$backupBaseName*" -File).Count + 1 | |
# get current log file | |
$logFile = Get-ChildItem -Path $nginxFolder -Filter "$logType.log" -File | |
# Check if file size exceeds the maximum size or if it's a new day | |
if (($logFile.Length -gt ($maxLogFileSizeMB * 1MB)) -or ($logFile.LastWriteTime -lt (Get-Date).Date)) { | |
# backup log, format as access.log.YYYYMMDD-count | |
$logFile | Rename-Item -NewName { $_.Name -replace "$logType.log", "$backupBaseName-$logCount" } | |
# get backup log file which name contain access or error | |
$backupLogFiles = Get-ChildItem -Path $nginxFolder -Filter "$logType.log.*" -File | |
# delete backup log which is older than keepLogCount | |
$backupLogFiles | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-$keepLogCount) } | Remove-Item | |
} | |
} | |
# reopen nginx service, need run as adminstrator | |
Restart-Service -Name nginx |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment