[개발] IIS 로그파일 자동 압축 및 삭제 (PowerShell 스크립트)

View this thread on: d.buzz | hive.blog | peakd.com | ecency.com
·@segyepark·
0.000 HBD
[개발] IIS 로그파일 자동 압축 및 삭제 (PowerShell 스크립트)
안녕하세요. 박세계입니다.

각종 로그파일은 불필요해 보이지만 막상 명확하지 않은 오류 발생시 큰 도움이 되는 경우가 많습니다. 하지만 보통의 경우 많은 디스크 공간을 차지해서 주기적으로 정리를 해줘야 하는 번거로움이 있습니다. 가만히 장기간 놔둘 경우 디스크 공간을 꽉 채워서 서비스 중단까지도 유발하기에 주기적인 정리는 필수입니다.

본 글에서는 Windows 웹서버 IIS에서 생성하는 로그파일을 자동 압축 및 삭제하는 PowerShell 스크립트를 공유하고자 합니다. 제가 정확히 원하는 스크립트를 찾을 수 없어 구글링을 통해 직접 만들었습니다. IIS 로그파일 정리를 기준으로 작성했지만 수정을 통해 파일 정리를 원하는 모든 상황에 적용할 수 있습니다.

---

# 1. PowerShell 5.0 이상 설치 
파일 압축을 위한 `Compress-Archive`가 5.0 이상 부터 지원합니다. 다른 방법도 있지만 최신버전에서 지원하는 최신 명령어를 사용하는게 암튼 좋습니다.
* [Windows Management Framework 5.1](https://www.microsoft.com/en-us/download/details.aspx?id=54616)

Windows 10과 Windows Server 2016 이상은 이미 최신버전인 5.1이 설치되어 있습니다. Windows 버전별 PowerShell 설치 버전은 다음 글 참조 바랍니다.
* [Upgrading existing Windows PowerShell](https://docs.microsoft.com/en-us/powershell/scripting/setup/installing-windows-powershell?view=powershell-6#upgrading-existing-windows-powershell)

# 2. PowerShell 스크립트 작성

다음 스크립트를 복사해서 `CompressAndCleanUpIISLogs.ps1` 이름으로 저장합니다. 저장 경로는 `C:\batch_jobs`로 하겠습니다.

스크립트 최상단의 `$SavingDays = 60`만 원하는데로 조절하면 됩니다. 그대로 두면 최근 60일간 생성된 로그파일만 남기고 모두 삭제합니다.

```
# Set this value as you want (Keep log files for this value)
$SavingDays = 60

# Initialize variables
$Today = (Get-Date).Date
$LastDayToKeep = $Today.AddDays(-$SavingDays)

# Clean up old log files
Get-ChildItem -Path $env:SystemDrive\inetpub\logs\LogFiles\w3svc*\* -Recurse | Where {$PSItem.LastWriteTime -lt $LastDayToKeep} | Remove-Item

If($? -eq $false)
{
    Return
}

# Compress log files except for today's one
Get-ChildItem -Path $env:SystemDrive\inetpub\logs\LogFiles\w3svc*\*.log -Recurse | Where {$PSItem.LastWriteTime -lt $Today} |
    ForEach-Object -Process {
        Compress-Archive -Path $PSItem.FullName -Update -DestinationPath "$($PSItem.DirectoryName)\$($PSItem.BaseName).zip"
        Remove-Item $PSItem.FullName
    }

If($? -eq $false)
{
    Return
}
```

스크립트 내용 요약입니다. 정리 작업은 모든 웹사이트의 모든 로그파일에 적용됩니다.

1. '오늘 로그파일 + 최근 60일 로그파일' 제외 모든 파일 삭제
1. 오늘 로그파일 제외 남아있는 모든 과거 로그파일 압축/삭제 (로그파일명.log -> 로그파일명.zip)

# 3. PowerShell 스크립트 실행

`Command Prompt`에서 다음과 같이 실행합니다.

`C:\>powershell C:\batch_jobs\CompressAndCleanUpIISLogs.ps1`

`Task Scheduler`에 등록하여 매일 실행되게 하면 됩니다. 스케줄링 설정 방법은 생략하겠습니다.

---

스크립트 실행 전과 후의 결과는 다음과 같습니다. 실행일은 '2018년 03월 02일' 입니다.

# 실행 전

![before-iis-logs-cleanup.png](https://steemitimages.com/DQmSeRQ3465XRVrs4YWJdqv1KRjZvmzQUPj5nQBMN92qaN1/before-iis-logs-cleanup.png)

# 실행 후

![after-iis-logs-cleanup.png](https://steemitimages.com/DQmVitHogwDKYqi8er2Yh95Jp7qT3DZLmWrqitfYCWVXcqe/after-iis-logs-cleanup.png)

실행 결과 요약입니다.

1. 60일 이전 파일 삭제
1. 계속 로깅이 되야 하는 당일 파일 `u_ex180302.log`는 미압축
1. 나머지 모든 파일 개별 압축

압축 후 파일당 10-15배 가량 용량이 줄어드는 걸 볼 수 있습니다. 차후 분석이 필요한 파일만 압축을 풀어서 확인하면 됩니다.
👍 , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,