This SharePoint tutorial, we will discuss, how to write to SharePoint uls logs using PowerShell in SharePoint 2013/2016. Also, we will see how to write logs to ULS logs using the SharePoint server object model.
SharePoint maintains Logs and Exceptions of SharePoint in ULS (Unified Logging Service). By default SharePoint stored in .log files in 15 hive folder (C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\LOGS). But you can change the default path to some other location.
In real-world scenarios to get details from ULS logs is difficult without using a tool, You can use SharePoint LogViewer to get logs details in SharePoint 2013.
Most of the time, SharePoint through a Correlation ID instead of the real error details. By using PowerShell you can retrieve original error messages based on correlation id. You can read: How to find uls log details based on correlation id using PowerShell in SharePoint 2016/2013.
We can also write our custom messages to ULS logs using the PowerShell or SharePoint server object model.
Write to ULS log using PowerShell in SharePoint
Below is the PowerShell code to write to ULS logs. We can put the below code in Windows PowerShell ISE
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue $diagSvc = [Microsoft.SharePoint.Administration.SPDiagnosticsService]::Local $category = new-object Microsoft.SharePoint.Administration.SPDiagnosticsCategory("My Custom Category", [Microsoft.SharePoint.Administration.TraceSeverity]::Monitorable, [Microsoft.SharePoint.Administration.EventSeverity]::Error ) $diagSvc.WriteTrace(0, $category, [Microsoft.SharePoint.Administration.TraceSeverity]::Monitorable, "This is our custom error message writted from PowerShell" )
After this if you want to check in ULS logs file you can see it will write like below:
05/10/2016 12:22:14.58 PowerShell_ISE.exe (0x9598) 0x65C4 Unknown My Custom Category 00000 Monitorable This is our custom error message writted from PowerShell cf54b83a-a9d2-0006-4a21-56cfd2a9d101
Write to ULS logs using the SharePoint server object model
SPDiagnosticsCategory category = new SPDiagnosticsCategory("My Custom Category",TraceSeverity.High,EventSeverity.ErrorCritical); SPDiagnosticsService.Local.WriteTrace(0,category,TraceSeverity.High,"This is our custom error message writted from SharePoint 2013 Server object model");
I hope this will be helpful to Write to ULS log using PowerShell in SharePoint 2013/2016. Also, we checked how to write logs to ULS logs using the SharePoint server object model.
Bhawana Rathore is a Microsoft MVP (3 times in Office Apps & Services) and a passionate SharePoint Consultant, having around 10 years of IT experience in the industry, as well as in .Net technologies. She likes to share her technical expertise in EnjoySharePoint.com and SPGuides.com