公司将服务器上的Nginx日志上传到阿里云上进行分析,服务器上的Nginx日志就需要及时清理。使用Powershell脚本,将其配置为定时任务。
主要分为两部分功能,第一部分将access.log和error.log文件中的日志实现按天分割,第二部分将最后修改日期距离当前日期超过30天文件删除。
# function: Cut nginx log files by date and clean them regularly.
# set the path to nginx log files
$log_dir="D:Nginxnginx-1.18.0logs"
# The format is as follows: 20200727
$time=get-date -Format "yyyyMMddHHmmss"
# 取出access.log中的旧日志写入新的文件
if(test-path $log_dir/access.log)
{
try {
$newfile=new-item $log_dir/access.$time.log
$oldlogs = get-content -path $log_dir/access.log -Encoding unicode
#清空access.log文件
clear-content -path $log_dir/access.log
Add-Content -path $newfile -value $oldlogs -Encoding unicode
}
Catch{
Write-Host "访问失败。错误原因:" $($error[0])
}
}else {
break;
}
# 取出error.log中旧日志
if(test-path $log_dir/error.log)
{
try {
$newfile=new-item $log_dir/error.$time.log
$oldlogs=get-content -path $log_dir/error.log
#清空error.log文件
clear-content -path $log_dir/error.log
Add-Content -path $newfile -value $oldlogs
}Catch{
Write-Host "访问失败。错误原因:" $($error[0])
}
}
else {
break;
}
# delete 30 days ago nginx log files
$TimeOutDays=30
$allFiles=get-childitem -path $log_dir -Exclude "nginx.pid"
foreach ($file in $allFiles)
{
$daypan=((get-date)-$file.lastwritetime).days
if ($daypan -gt $TimeOutDays)
{
remove-item $file.fullname -Recurse -force
}
}
最后将powershell脚本设置为定时任务
1.打开windows任务计划程序,新建任务
2.设置任务运行时间
3.填上powershell路径和脚本路径



