sharepoint logging/trace - sharepoint

how can i perform logging in sharepoint. i want to use tracing.
so that it logs in the 12 hive logs.

Microsoft provide an example:
http://msdn.microsoft.com/en-us/library/aa979522.aspx
This sample writes to the ULS log using the native trace methods, so a bit of pInvoke is used in the code.
You can then control the type of logging event in your code such as:
TraceProvider.WriteTrace(0, TraceProvider.TraceSeverity.High, Guid.Empty, "MyExeName", "Product Name", "Category Name", "Sample Message");
The event throttling settings in central admin will still be honored with this approach.

My preferred approach is to write a custom HttpModule to trap and log all errors. After logging the error, you can redirect the user to an error page - this is the approach I've seen most used for custom error handling in SharePoint.
In your HttpModule, you can use an approach such as the one described by Daniel to write the exceptions to the ULS logs.
Here's a simple example of doing this:
Create a class that implements IHttpModule, and wire up the appropriate event in the Http pipeline:
public void Init(HttpApplication context)
{
context.Error += new EventHandler(context_Error);
}
In the context_Error event, go through all the errors and log them ...
void context_Error(object sender, EventArgs e)
{
TraceProvider.RegisterTraceProvider();
foreach (var ex in HttpContext.Current.AllErrors)
{
TraceProvider.WriteTrace(0,
TraceProvider.TraceSeverity.Exception,
Guid.NewGuid(),
Assembly.GetExecutingAssembly().FullName,
"<your application name>",
"<exception category>",
ex.ToString());
}
TraceProvider.UnregisterTraceProvider();
HttpContext.Current.Server.ClearError();
HttpContext.Current.Response.Clear();
HttpContext.Current.Server.Transfer("/_layouts/Error500.aspx");
}
You of course have to wrap this all up into a feature (scoped at the Web Application level) and deploy it to SharePoint.
Note that your entry in the section of web.config for this custom error http module needs to be first in the list. The order in which the http modules are listed in the section matters, and the custom error http module should always execute first.

(SharePoint 2007?) From Central Admin, go to Operations->Diagnostic Logging, "Trace Log" and "Event Throttling" are what you're looking for.
Select a category in "Event Throttling" and select least critical errors for both the event and trace logs. Then, select a path for the trace logs (mine was defaulted to ..12\LOGS) and supply a max number of logs and the number of minutes to use each log file.

I wrote some blog posts that will help you out. What i suggest is using the BCL logging classes (System.Diagnostics) and creating a custom TraceListner that writes to the SharePoint ULS logs.
http://sharepoint.nailhead.net/2008/04/instrumentation-logging-for-sharepoint.html

If you´re using MOSS, you can use this:
Microsoft.Office.Server.Diagnostics.PortalLog.LogString("Message");
Keep in mind that according to Microsoft documentation - LogString is reserved for internal use and is not intended to be used directly from your code.
For more details refer this link -
https://msdn.microsoft.com/en-us/library/office/microsoft.office.server.diagnostics.portallog_members.aspx

Related

How do I configure Trace statements to go to the Portal in Windows Azure Mobile Services

I have a .Net back end mobile service and I would like my System.Diagnostics.Trace statements to go to the same destination as ApiServices.Log (i.e. the portal).
The reason for this is that I don't want to pass ITraceWriter down to my data tier due to the dependencies it adds (System.Web.Http etc).
I started to look at an approach where I would add to the trace listeners collection, similar to as described here:
http://blog.tylerdoerksen.com/2012/04/20/logging-in-azure-part-3-traceevent-logs/
But this adds an instance of DiagnosticMonitorTraceListener which doesn't exist by default in a MobileService as this lives in Microsoft.WindowsAzure.Diagnostics.
Does anyone know how to do this?
Thanks
F
In general, trace messages are written to the logs regardless of where they come from. For example, if I have a custom controller like this:
public string Get()
{
IHubContext hubContext = Services.GetRealtime<ChatHub>();
Trace.WriteLine("something!");
Trace.TraceError("error");
Trace.TraceInformation("info");
hubContext.Clients.All.hello("Hello Chat Hub clients from custom controller!");
return "Hello from custom controller!";
}
then "error" and "info" are written as you would expect. In fact, you can find the logs directly from within VS by using the Service Explorer and then Azure and Mobile Services. Right click on your service and select View Logs.
The only wrinkle is that verbose messages are not written as the default log level is Info. You can work around this by setting the level manually through the Kudu site:
https://.scm.azure-mobile.net
Then under the "Debug Console" drill down to Site/diagnostics and edit the file settings.json. It should look something like this:
"AzureDriveEnabled":true,"AzureDriveTraceLevel":"Information","AzureTableEnabled":false,"AzureTableTraceLevel":"Error","AzureBlobEnabled":false,"AzureBlobTraceLevel":"Error"}
Change the Information value to Verbose and you will get verbose messages as well.
Hope this helps!
Henrik

My custom Windows Service is not writing to my custom Event Log

I have written a custom Windows Service that writes data to a custom Event Log (in the Windows Event Viewer).
For dev'ing the biz logic that the service uses, I created a Windows Form which simulates the Start/Stop methods of the Windows Service.
When executing the biz logic via the Windows Forms, info is successfully written to my custom Event Log. However, when I run the same biz logic from the custom Windows Service, information is failing to be written to the Event Log.
To be clear, I have written a library (.dll) that does all the work that I want my custom service to do - including the create/write to the custom Event Log. My Form application references this library as does my Windows Service.
Thinking the problem is a security issue, I manually set the custom Windows Service to "Log on" as "Administrator", but the service still did not write to the Event Log.
I'm stuck on how to even troubleshoot this problem since I can't debug and step into the code when I run the service (if there is a way to debug a service, please share).
Do you have any ideas as to what could be causing my service to fail to write to the event log?
I use it like this. There can be some typos. Writed it on my phone browser...
public class MyClass
{
private EventLog eventLog = new EventLog();
public void MyClass()
{
if (!System.Diagnostics.EventLog.SourceExists("MyLogSource"))
System.Diagnostics.EventLog.CreateEventSource("MyLogSource", "MyLogSource_Log");
eventLog.Source = "MyLogSource";
eventLog.Log = "MyLogSource_Log";
}
private void MyLogWrite()
{
eventLog.WriteEntry(ex.ToString(), EventLogEntryType.Error);
}
}
To debug a running service you need to attach to the process. See here for the steps.
You could also add parameter checking to the Main entry point and have a combination service and console app which would start based on some flag. See this SO post for a good example but here's a snippet:
using System;
using System.ServiceProcess;
namespace WindowsService1
{
static class Program
{
static void Main(string[] args)
{
if (args == null)
{
Console.WriteLine("Starting service...");
ServiceBase.Run(new ServiceBase[] { new Service1() });
}
else
{
Console.WriteLine("Hi, not from service: " + args[0]);
}
}
}
}
The above starts the app in console mode if there any parameters exist and in service mode if there are no parameters. Of course it can be much fancier but that's the gist of the switch.
I discovered why my service wasn't writing to the Event Log.
The problem had nothing to do with any part of the code/security/etc that was attempting to write to the EL. The problem was that my service wasn't successfully collecting the information that is written to the EL - therefore, the service wasn't even attempting to write the log.
Now that I fixed the code that collects the data, data is successfully writing to the event log.
I'm open to having this question closed since the question was amiss to the real problem.

how to view azure diagnostics Log

I am not able to find out how to see azure diagnostics logs. Code which I wrote is as follows.
DiagnosticMonitorConfiguration config = iagnosticMonitor.GetDefaultInitialConfiguration();
System.Diagnostics.Trace.Listeners.Add(new Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener());
config.Logs.ScheduledTransferLogLevelFilter = LogLevel.Information;
config.WindowsEventLog.ScheduledTransferPeriod = System.TimeSpan.FromMinutes(1.0);
DiagnosticMonitor.Start("Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString", config);
then I added Trace.WriteLine("some message"); in the code. Now where do I find those messages. I checked in Visual Studio server explorer, where I added my storage account reference. wad-control-container has only config files.
You might want to take a look at this blog post by Michael S. Collier. A setting in your cloud project might cause the logs to end up in an other place than you would expect them to:
http://michaelcollier.wordpress.com/2012/04/02/where-is-my-windows-azure-diagnostics-data/
Update:
Note that you'll have to take care of every small detail to make everything work.
Where are you writing Trace.WriteLine("some message"); ? Is it in your WebRole.cs? If that's the case, you'll need to configure the trace listener for the WebRole.cs (this runs in an other process, different than your actual web application).
Here is an example how you can set up the trace listener in the WebRole.cs class:
System.Diagnostics.Trace.Listeners.Add(new Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener());
System.Diagnostics.Trace.AutoFlush = true;
After setting that up, you can use Trace.WriteLine.
This is a good step by step on how to enable diagnostics:
http://www.windowsazure.com/en-us/develop/net/common-tasks/diagnostics/?sec=commontasks
I wrote a tool that allows you to view Azure Diagnostic information.. check it out
AzTools - Azure Diagnostic Viewer
Click here to see how you could use this tool

Extending log4net - Adding additional data to each log

We're working on logging in our applications, using log4net. We'd like to capture certain information automatically with every call. The code calling log.Info or log.Warn should call them normally, without specify this information.
I'm looking for a way to create something we can plug into log4net. Something between the ILog applications use to log and the appenders, so that we can put this information into the log message somehow. Either into ThreadContext, or the LogEventInfo.
The information we're looking to capture is asp.net related; the request url, user agent, etc. There's also some information from the apps .config file we want to include (an application id).
I want to get between the normal ILog.Info and appender so that this information is also automatically included for 3rd party libraries which also use log4net (Nhibernate, NServiceBus, etc).
Any suggestions on where the extensibility I want would be?
Thanks
What you are looking for is called log event context. This tutorial explains how it works:
http://www.beefycode.com/post/Log4Net-Tutorial-pt-6-Log-Event-Context.aspx
In particular the chapter 'Calculated Context Values' will interesting for you.
Update:
My idea was to use the global context. It is easy to see how this works for something like application ID (in fact there you do not even need a calculated context object). Dynamic information like request url could be done like this:
public class RequestUrlContext
{
public override string ToString()
{
string url;
// retrieve url from request
return url;
}
}
The object is global but the method is called on the thread that handles the request and thus you get the correct information. I also recommend that you create one class per "information entity" so that you have a lot of flexibility with the output in the log destination.

SharePoint and deployment of global.asax code

I want to start logging some custom messages into the ULS from my custom SharePoint code. My code is running inside list item receivers attached to some lists. I'd like to configure this logging mechanism within the application start event handler in global.asax. What's the best-practices way to deploy a SharePoint solution package that modifies global.asax?
I don't know about "best practice", but I would be quite keen on making the edits via code in the feature reciever.
With a line that backs up the file for later restoration.
For logging, we have used Scott hilliers code here to create a trace provider to log with.
Works a treat.
I should clarify that we use a static readonly wrapper for the trace provider
static readonly Log instance = new Log();
that registers itself with the code
SPFarm farm = SPFarm.Local;
Guid traceGuid = farm.TraceSessionGuid;
unit result = NativeMethods.RegisterTraceGuids(ControlCallback, null, ref traceGuid, 0, IntPrt.Zero, null, null, out hTraceReg);
System.Diagnostics.Debug.Assert(result==NativeMethods.ERROR_SUCCESS, "TraceRegister result = " + result.ToString());
Gah!
This then gets instanciated only once and we use the destructor to unregister it.

Resources