In this blog post I’m going to show you how to implement the Patterns and practices logging in a sanboxed solution.
If you haven’t read Sandboxed logging part 1 I advise you to read it first before continuing this blog post :).
Logging in a Sandboxed solution.
I uploaded an example that you can use at our codeplex site. If you open the zip file you will see the following folder and files. It is recommended to download the example because the necessary wsp and DLL are also in the zip file :).
Create a new Empty SharePoint Solution and name it “Sandboxed.Logging.Example”.
Check “Deploy as a sandboxed solution”.
Reference the following DLL files “Microsoft.Practices.ServiceLocation”,”Microsoft.Practices.SharePoint.Common”. The DLL files can be found in the zip file you downloaded from our codeplex.
Add a new webpart and name it “SandboxedLoggingTest”.
Use the following classes.
Create the following private variables.
private IServiceLocator _serviceLocator;
private ILogger _logger;
Override the OnInt method.
protected override void OnInit(EventArgs e)
_serviceLocator = SharePointServiceLocator.GetCurrent();
_logger = _serviceLocator.GetInstance<ILogger>();
Where going to create 2 buttons. The first one will log to the event viewer and ULS logs. The second one will only log to the ULS logs. In the “CreateChildControls” add the following code.
Button btnLogToOperations = new Button();
btnLogToOperations.Text = "LogToOperations";
btnLogToOperations.Click += new EventHandler(btnLogToOperations_Click);
Button btnTraceToDeveloper = new Button();
btnTraceToDeveloper.Text = "TraceToDeveloper";
btnTraceToDeveloper.Click += new EventHandler(btnTraceToDeveloper_Click);
Add the following code to btnLogToOperations_Click.
LogToOperations will log the message or exception to the event viewer and the ULS Logs.
void btnLogToOperations_Click(object sender, EventArgs e)
_logger.LogToOperations("I'm int he event viewer and the ULS logs", 2159, SandboxEventSeverity.ErrorCritical, "VNTG/Webpart");
Add the following code to btnTraceToDeveloper_Click.
TraceToDeveloper will log the message or exception to the ULS logs.
void btnTraceToDeveloper_Click(object sender, EventArgs e)
_logger.TraceToDeveloper("I'm in the ULS logs", 2159, "VNTG/Webpart");
Deploy the solution and add the webpart to a page.
Click on LogToOperations.
Click on TraceToDeveloper.