Search code examples
c#nlogsustainsys-saml2

How to setup NLog with Sustainsys.Saml2


I have an ASP.Net Web Forms app where I just integrated Sustainsys.Saml2 library.

I've never used any sort of logging mechanism and I'm trying to figure out how to add or create an ILoggerAdapter for the library stated on their troubleshooting page.

I've decided to use NLog (please feel free to recommend a different one) and either I'm not understanding this well, or am not using the right keyword to search for what I need/want, or their isn't a lot of documentation on it.

Currently, I'm using the HttpModule version of Sustainsys.Saml2. Any other information available upon request.

Any help would be great.

Currently, I'm configuring the Sustainsys.Saml2 library through both web.config and the global.asax files. Here's the class my global.asax calls:

public class Saml2Config {
    private static bool _alreadyInitialized;
    private static readonly object Lock = new object();

    public static void Initialize() {
        if (_alreadyInitialized) {
            return;
        }

        lock (Lock) {
            if (_alreadyInitialized) {
                return;
            }

            var domain = PageHelper.GetDomainURL(true);

            Sustainsys.Saml2.Configuration.Options.FromConfiguration.SPOptions.EntityId.Id = $"{domain}/federation/Saml2";
            Sustainsys.Saml2.Configuration.Options.FromConfiguration.SPOptions.ModulePath = "/federation/Saml2";
            Sustainsys.Saml2.Configuration.Options.FromConfiguration.SPOptions.ReturnUrl = new Uri($"{domain}/mybarry");
            Sustainsys.Saml2.Configuration.Options.FromConfiguration.SPOptions.PublicOrigin = new Uri($"{domain}");

            Sustainsys.Saml2.Configuration.Options.FromConfiguration.SPOptions.Logger = new NullLoggerAdapter();

            _alreadyInitialized = true;
        }
    }
}

Solution

  • The interface is pretty straightforward

    public interface ILoggerAdapter
    {
        void WriteInformation(string message);
    
        void WriteError(string message, Exception ex);
    
        void WriteVerbose(string message);
    }
    

    I would implement it as follows:

    public class NLogAdapter : ILoggerAdapter
    {
        private static Logger Logger = LogManager.GetLogger("Saml2");
    
        public void WriteInformation(string message)
        {
            Logger.Info(message);
        }
    
        public void WriteError(string message, Exception ex)
        {
            Logger.Error(ex, message);
        }
    
        public void WriteVerbose(string message)
        {
            Logger.Debug(message);
        }
    }
    

    And finally set it:

    Sustainsys.Saml2.Configuration.Options.FromConfiguration.SPOptions.Logger = new NLogAdapter();