栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

Powershell 脚本实现分割Nginx日志并清理

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Powershell 脚本实现分割Nginx日志并清理

公司将服务器上的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路径和脚本路径

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/642688.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号