Логи IIS — очистка
Веб-сервер IIS в процессе своей работы генерирует достаточно большие объемы log-файлов. Все бы ничего, но по умолчанию логи IIS располагаются на системном диске , которому обычно не предоставляют большой объем. Хорошо, если у вас виртуальная машина и вы можете просто не обращать внимание на нехватку диска C:\, увеличивая его объем по необходимости, благо функционал виртуальных машин Hyper-V второго поколения позволяет увеличивать размер даже системного диска без выключения сервера, прямо налету. А если у вас такой возможности нет? В таком случае разрастание логов может стать для вас серьезной проблемой.
В статье я расскажу как обращаться с log-файлами IIS и автоматизировать процесс удаления.
Если вам интересна тематика Windows Server, рекомендую обратиться к тегу Windows Server на моем блоге.
Логи IIS
По умолчанию логи IIS располагаются в каталоге %SystemDrive%\inetpub\logs\LogFiles. Сигналом для их очистки может служить истощающееся быстрыми темпами свободное место системного диска. В этом случае системные администраторы начинают искать что же занимает столько места и благополучно пропускают папку inetpub, поскольку по умолчанию она практически ничего не весит:
Но почему? Дело в том, что изначально вы не имеете разрешений на вложенные папки, следовательно не можете увидеть их реальный объем:
Попробуйте зайти в каждую подпапку каталога %SystemDrive%\inetpub\logs\LogFiles, соглашаясь с назначением необходимых разрешений и в итоге увидите, что реальный объем папок не так уж и мал:
Разумеется у меня приведены в пример скриншоты с тестового сервера. Объем логов серверов в продакшене может достигать десятков и сотен гигабайт совершенно спокойно.
Итак, проблема найдена, пора заняться очисткой. Теоретически её можно проводить и вручную, но в этом нет никакого смысла и проще все сделать скриптами, в некоторых случаях достаточно даже одной команды PowerShell. В одной из статей по Exchange 2013 (см. Очистка папки Logging Exchange 2013) я уже рассматривал вопрос автоматизации процесса очистки логов, но не помешает напомнить о нем и в этой статье.
Команда для очистки log-файлов в нашем случае будет выглядеть следующим образом:
IIS: Where can I find the IIS logs?
I’m trying to set up an application from a third party, which requires a supporting website hosted in my local IIS. I’ve created a website exactly as explained in their install guide, but am having some problems, and would like to see what the IIS log has to say. Embarrassingly enough, the problem is I can’t find the log files!
So my question is: Where does IIS7 store logs by default?
10 Answers 10
I think the default place for access logs is
Otherwise, check under IIS Manager, select the computer on the left pane, and in the middle pane, go under «Logging» in the IIS area. There you will se the default location for all sites (this is however overridable on all sites)
You could also look into
Which will contain similar log files that only represents errors.
I believe this is an easier way of knowing where your IIS logs are, rather than just assuming a default location:
Go to your IIS site, e.g. Default, click on it, and you should see «Logging» to the right if logging is enabled:
Open it and you should see the folder right there:
You are welcome!
I’m adding this answer because after researching the web, I ended up at this answer but still didn’t know which subfolder of the IIS logs folder to look in.
If your server has multiple websites, you will need to know the IIS ID for the site. An easy way to get this in IIS is to simply click on the Sites folder in the left panel. The ID for each site is shown in the right panel.
Once you know the ID, let’s call it n, the corresponding logs are in the W3SVCn subfolder of the IIS logs folder. So, if your website ID is 4, say, and the IIS logs are in the default location, then the logs are in this folder:
- Answer by @jishi tells where the logs are by default.
- Answer by @Rafid explains how to find actual location (maybe not default).
- Answer by @Bergius gives a programmatic way to find the log folder location for a specific website, taking ID into account, without using IIS.
Windows system32 logfiles w3svc1
Question
We have recently built up an SCCM server and our «c drive» is filling up due to this directory, can we delete these files and if not how do we get this directory under control.
We are running windows server 2008
WSUS
SCCM
Answers
I trim mine with the following command which creates a scheduled task to do it :-
at 12:00 /EVERY:Su Forfiles.exe -p C:\WINDOWS\system32\LogFiles\W3SVC1 -m *.log -d -30 -c \»Cmd.exe /C del @path\»
This will run every Sunday, and will trim files in that folder older than 30 days. Adjust to suit.
Regards,
Tom Watson,
E-Mail: Tom_. @.
Blog: http://myitforum.com/cs2/blogs/tom_watson
You can absolutely delete these log files or zip them or turn on NTFS compression. These log files are mainly for troubleshooting and reviewing security. If neither are of immediate interest to you, then turn off logging altogether or write a script to delete them periodically. It’s not like ConfigMgr is actually hosting any critical business information and you should have other safe guards in place anyway.
Jason | http://myitforum.com/cs2/blogs/jsandys | http://blogs.catapultsystems.com/jsandys/default.aspx | Twitter @JasonSandys
- Proposed as answer by Jason Sandys [MSFT] MVP Monday, December 28, 2009 8:02 PM
- Marked as answer by Yog Li Monday, January 4, 2010 10:33 AM
All replies
You can absolutely delete these log files or zip them or turn on NTFS compression. These log files are mainly for troubleshooting and reviewing security. If neither are of immediate interest to you, then turn off logging altogether or write a script to delete them periodically. It’s not like ConfigMgr is actually hosting any critical business information and you should have other safe guards in place anyway.
Jason | http://myitforum.com/cs2/blogs/jsandys | http://blogs.catapultsystems.com/jsandys/default.aspx | Twitter @JasonSandys
- Proposed as answer by Jason Sandys [MSFT] MVP Monday, December 28, 2009 8:02 PM
- Marked as answer by Yog Li Monday, January 4, 2010 10:33 AM
I trim mine with the following command which creates a scheduled task to do it :-
at 12:00 /EVERY:Su Forfiles.exe -p C:\WINDOWS\system32\LogFiles\W3SVC1 -m *.log -d -30 -c \»Cmd.exe /C del @path\»
This will run every Sunday, and will trim files in that folder older than 30 days. Adjust to suit.
Regards,
Tom Watson,
E-Mail: Tom_. @.
Blog: http://myitforum.com/cs2/blogs/tom_watson
Where can I disable this LOG? Is it necessary, I never use it.
Here we can disable the IIS log files
Go To IIS console -> and Right click WebSite Property and click web site TAB find the Enable logging Next Step ->Uncheck the Enable Logging and restart the IISADMIN services after restart the service IIS log files are disbled
This was a great help. I’ve created a post at http://www.itbangbang.net/2011/10/are-w3svc1-log-files-getting-very-large.html to pass on your information. Thanks!
I trim mine with the following command which creates a scheduled task to do it :-
at 12:00 /EVERY:Su Forfiles.exe -p C:\WINDOWS\system32\LogFiles\W3SVC1 -m *.log -d -30 -c \»Cmd.exe /C del @path\»
This will run every Sunday, and will trim files in that folder older than 30 days. Adjust to suit.
Regards,
Tom Watson,
E-Mail: Tom_. @.
Blog: http://myitforum.com/cs2/blogs/tom_watson
This was a great thread. Cleared over 50 GB from a server today! Thanks,
Regards,
Tom Watson,
E-Mail: Tom_. @.
Blog: http://myitforum.com/cs2/blogs/tom_watson
i copied and pasted your forfiles.exe command on a 2008 windows server R2 and got the following error:
C:\IISSEPM\W3SVC2>Forfiles.exe -p C:\IISSEPM\W3SVC2 -m *.log -d -30 -c \»Cmd.exe /C del @path\»
ERROR: Invalid syntax. ‘/C’ option is not allowed more than ‘1’ time(s).
Type «FORFILES /?» for usage.
Jason | http://blog.configmgrftw.com | Twitter @JasonSandys
not sure what «smart quotes» are — i tried substituting the quotes i had copied and pasted w/ double quotes typed in manually — no luck.
i then removed the back slashes (\) and viola, it worked — no idea why.
thx for your assistance.
Regards,
Tom Watson,
E-Mail: Tom_. @.
Blog: http://myitforum.com/cs2/blogs/tom_watson
Tom sorry to be a pain but how do you create this script??
Usually when i start ten tas it is asking for an application !
Where to run this from?
I started Task manager in SBS 2008, not sure of the commands there.
The mistake I found in Tom Watson’s script is the added backslash \ before the Cmd.exe string resulting in the following:
ERROR: Invalid syntax. ‘/C’ option is not allowed more than ‘1’ time(s).
Type «FORFILES /?» for usage.
The fix, at least in my case was to remove the backslash \ as shown below.
Windows 2003
at 12:00 /EVERY:Su Forfiles.exe -p C:\WINDOWS\system32\LogFiles\W3SVC1 -m *.log -d -30 -c «Cmd.exe /C del @path\»
Windows 2008
at 12:00 /EVERY:Su Forfiles.exe -p C:\inetpub\logs\LogFiles\W3SVC1 -m *.log -d -30 -c «Cmd.exe /C del @path\»
I was wondering is we can get both «daily» and «max size» of the W3SVC logs. Since we have enabled «daily» generation of logs, it gets up to 400MB, but seldom it reaches more than a GB, which is when we get issue in opening the log files in Server itself (in notepad, since we don’t use 3rd party softwares to open log files). From GUI we can enable either of these two options. Is there something via command or else?
I trim mine with the following command which creates a scheduled task to do it :-
at 12:00 /EVERY:Su Forfiles.exe -p C:\WINDOWS\system32\LogFiles\W3SVC1 -m *.log -d -30 -c \»Cmd.exe /C del @path\»
This will run every Sunday, and will trim files in that folder older than 30 days. Adjust to suit.
Regards,
Tom Watson,
E-Mail: Tom_. @.
Blog: http://myitforum.com/cs2/blogs/tom_watson
Absolutely fantastic! Win2008R2, Exch2010 works perfectly. Thanks Tom
You saved my bacon. This was the answer for clearing the logs on my Exchange 2010 Server. When my C:\ drive dropped below 5% free space, the Transport hub shut down and we stopped receiving external email.
Once I started purging this directory emails started flowing. Great answer, thanks a million!
I hadn’t heard of ForFiles so I looked at the Microsoft documentation for it. It uses slashes preceding the parameters instead of hyphens (e.g. » /p», » /d», etc). Can it accept either?
I thought I’d throw in a «for what it’s worth» reply because this was the first hit on one of my search efforts.
My log files had increased dramatically for our small environment (from 1-2MB in size to 50-100MB). I discovered Microsoft’s Log Parser 2.2 and it helped me review these messy things with a graphical interface.
I ran the graphical interface, loaded one of the «u_exYYMMDD.log» files and while reviewing some of the ActiveSync Reports, I noticed that one user’s phone had their login set to «domain/user» instead of «domain\user». That simple change to the backslash caused the log to go back to 1-2 MB per day. Without log parser, I don’t think I would have noticed that.
Log Parser 2.2: https://www.microsoft.com/en-us/download/details.aspx?id=24659
Just to help anyone else who stumbles across this
The AT command no longer works and has been replaced by SCHTASKS — New command for removing IIS logs weekly at 11:59am on Saturday
SchTasks /Create /SC WEEKLY /D SAT /TN «Remove IIS logs older than 7 days» /TR «Forfiles.exe -p C:\inetpub\logs\LogFiles\W3SVC1 -m *.log -d -7 -c \»Cmd.exe /C del @path\\»» /ST 11:59
Note the extra backslashes escaping the quotes around the forfiles command