向SharePoint的ULS日志中写入自己的跟踪信息

SharePoint中自定义的webpart, event handler, workflow非常常见. 这些集成了的东西如果报错很难排查. 这篇文章列出介绍简单的使用ULS日志的方法.

参考下面的资料来了解如何向ULS日志中写入信息

==============

SharePoint Trace Logs and the Unified Logging Service (ULS)

http://weblogs.asp.net/erobillard/archive/2008/07/31/sharepoint-trace-logs-and-the-unified-logging-service-uls.aspx

Writing to the Trace Log

http://msdn.microsoft.com/en-us/library/aa979595.aspx

Trace Log Example

http://msdn.microsoft.com/en-us/library/aa979522.aspx

知道了怎么写, 还需要知道要写什么. 排查错误最需要的信息, 就是丢出错误的代码位置. 知道了位置之后, 才可以展开相应的一些猜想, 验证, 或者再添入一些可疑对象字段的值的日志输出.

下面的代码段显示了如何从exception中拿到错误的行号等信息.

static void Main(string[] args)
{
    try
    {
        Fun1();
    }
    catch (Exception ex)
    {
        System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
        Console.WriteLine(trace.GetFrame(0).GetMethod().Name); //Get deepest error function.
        Console.WriteLine("Line: " + trace.GetFrame(0).GetFileLineNumber()); //Get error line number.
        Console.WriteLine("Column: " + trace.GetFrame(0).GetFileColumnNumber());
        Console.WriteLine(ex.ToString());//All in one! This one is simplest.
    }
}

static void Fun1()
{
    throw new Exception("An error has happened");
}

System.Diagnostics.StackTrace的GetFrame(index)方法可以得到StackFrame对象, Stack Frame的index是从0开始的, 0是最后一个入栈的stackframe.

原文地址:https://www.cnblogs.com/awpatp/p/1658280.html