Skip to content

Instantly share code, notes, and snippets.

@jiaming0708
Last active December 15, 2023 08:23
Show Gist options
  • Save jiaming0708/3e8cb7252f350ccdaeb595984595acd9 to your computer and use it in GitHub Desktop.
Save jiaming0708/3e8cb7252f350ccdaeb595984595acd9 to your computer and use it in GitHub Desktop.
nginx logrotate on windows
# 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