13

I am getting the following error when I try to write to the uls logs in sharepoint 2013:

System.ArgumentNullException : {"Value cannot be null.\r\nParameter name: category"}

The error is thrown in the second line in the code below.

  public static void LogError(string categoryName, string errorMessage)
    {
        SPDiagnosticsCategory category = LogService.Current.Areas[_DiagnosticAreaName].Categories[categoryName];
        LogService.Current.WriteTrace(0, **category**, TraceSeverity.High, errorMessage);
    }

Any idea why the category is null even though I pass it?

Markus
  • 357
  • 6
  • 20
Imir Hoxha
  • 1,905
  • 6
  • 28
  • 55

1 Answers1

18

You are probably passing a category that does not exist, so this

SPDiagnosticsCategory category = LogService.Current.Areas[_hamonDiagnosticAreaName].Categories[categoryName];

becomes null

in my provider, these are the categories available:

    public enum Category{
        Unexpected,
        High,
        Medium,
        Information
    }

Full code:

public class Logger : SPDiagnosticsServiceBase
{
    public static string DiagnosticAreaName = "Fishbone";
    private static Logger _Current;
    public static Logger Current
    {
        get
        {
            if (_Current == null)
            {
                _Current = new Logger();
            }

            return _Current;
        }
    }

    public Logger() : base("Fishbone Logging Service", SPFarm.Local)
    {

    }

    public enum Category{
        Unexpected,
        High,
        Medium,
        Information
    }

    protected override IEnumerable<SPDiagnosticsArea> ProvideAreas()
    {
        List<SPDiagnosticsArea> areas = new List<SPDiagnosticsArea>
        {
            new SPDiagnosticsArea(DiagnosticAreaName, new List<SPDiagnosticsCategory>
            {
                new SPDiagnosticsCategory("Unexpected", TraceSeverity.Unexpected, EventSeverity.Error),
                new SPDiagnosticsCategory("High", TraceSeverity.High, EventSeverity.Warning),
                new SPDiagnosticsCategory("Medium", TraceSeverity.Medium, EventSeverity.Information),
                new SPDiagnosticsCategory("Information", TraceSeverity.Verbose, EventSeverity.Information)
            })
        };

        return areas;
    }

    public static void WriteLog(Category categoryName, string source, string errorMessage)
    {
        SPDiagnosticsCategory category = Logger.Current.Areas[DiagnosticAreaName].Categories[categoryName.ToString()];
        Logger.Current.WriteTrace(0, category, category.TraceSeverity, string.Concat(source, ": ", errorMessage));
    }
}

used as

 Logger.WriteLog(Logger.Category.Unexpected, "Place of error", "Error message");
Robert Lindgren
  • 24,520
  • 12
  • 53
  • 79