@manhng

Welcome to my blog!

Simplest way to support logging from a VSTO AddIn

June 23, 2020 10:46

Simplest way to support logging from a VSTO AddIn (edit)

Simplest way to support logging from a VSTO AddIn

1) Using System.IO.File.Write to a Text file

https://johandorper.com/log/thread-safe-file-writing-csharp

https://jonlabelle.com/snippets/view/csharp/thread-safe-file-writing-in-csharp

https://www.c-sharpcorner.com/UploadFile/1d42da/readerwriterlockslim-class-in-C-Sharp-threading/

System.IO.File.AppendAllText(Filepath, Text);

2) Using Log4net

https://stackoverflow.com/questions/28541528/simplest-way-to-support-logging-from-a-vsto-addin

https://docs.microsoft.com/en-us/visualstudio/vsto/deploying-an-office-solution-by-using-windows-installer?redirectedfrom=MSDN&view=vs-2017

Folder Path:

%ProgramData%

%AppData%

File Path:

C:\Users\nvmanh\AppData\Roaming\MyAddIn_DATA\MyAddIn_Rolling.log

Member:

private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

Constructor:

log4net.Config.XmlConfigurator.Configure();

AssemblyInfo.cs: 

[assembly: log4net.Config.XmlConfigurator(Watch=true)]

It is relatively straightforward to setup log4net to handle simple (or complex) logging requirements. The log4net Tutorial on CodeProject provides a useful reference.

  1. Install log4net to your project using the NuGet Package Manager or Package Manager Console if you prefer.
  2. Add an App.config file if you don't have one already (right-click your project, select Add > New Item... and select Application Configuration File from Visual C# Items).
  3. Edit the App.config file to look something like this (replacing MyAddIn appropriately in the <file /> tag):

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <configSections>
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" requirePermission="false" />
      </configSections>
      <log4net>
        <root>
          <level value="ALL"/> 
          <appender-ref ref="RollingFileAppender"/>
        </root>
        <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
          <file value="${APPDATA}\MyAddIn_DATA\MyAddIn_Rolling.log" />
          <appendToFile value="true" />
          <rollingStyle value="Size" />
          <maxSizeRollBackups value="5" />
          <maximumFileSize value="5MB" />
          <staticLogFileName value="true" />
          <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date [%thread] %level %logger - %message%newline" />
          </layout>
        </appender>
      </log4net>
    </configuration>

    Log files will be saved to the user's roaming AppData (%appdata%) folder, keeping up to 5 rolling log files which do not exceed 5MB each.

  4. Add the following line to ThisAddIn_Startup() in ThisAddIn.cs (you will need to add a using log4net; directive):

    log4net.Config.XmlConfigurator.Configure();
  5. Add the following statement to any class which needs to implement logging:

    private static readonly log4net.ILog log = 
        log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  6. Events can then be logged using the log.Info, log.Warn, log.Error, log.Fatal and other methods provided by log4net.

You may get schema warning messages because log4net does not include a schema, and Visual Studio cannot then validate the config section. In that case, download the schema file from http://csharptest.net/downloads/schema/log4net.xsd to somewhere accessible. The location C:\Program Files\Microsoft Visual Studio 10.0\Xml\Schemas has been suggested elsewhere.

Select your App.config file in Visual Studio, and click into the editor. You should get an XML menu item. From there, select Schemas... and add the log4net.xsd file from where you saved it.

Note that you can also use log4net to log to the Event Viewer but you will run into the same permission issues raised in the initial question.

Categories

Recent posts