Running NLog in WPF Browser Application and other partially trusted environments

NLog is a pretty slick logging library, no doubts about that. However if you try to use it from a partially trusted environment you are facing some problems. The solution is to fix two things in the sources and recompile them. Here is the recipe:

1. Open solution NLog.vs2005.sln in Visual Studio. If you have no special needs you’ll need to recompile just the project NLog.vs2005 – you can safely remove others from the solution.

2. Add [assembly: System.Security.AllowPartiallyTrustedCallers] line to AssemblyInfo.cs file. With this change you are allowing partially trusted callers. This might not be enough. See the next paragraph.

3. If you don’t provide explicit configuration then NLog will try to read from environmental variable and thus causing a SecurityException due to EnvironmentPermission request which is not granted by default. To avoid this you’ll have to comment a piece of code in the LogFactory.Configuration property:

if (_config == null)
{
    if (EnvironmentHelper.GetSafeEnvironmentVariable("NLOG_GLOBAL_CONFIG_FILE") != null)
    {
        string configFile = Environment.GetEnvironmentVariable("NLOG_GLOBAL_CONFIG_FILE");
        if (File.Exists(configFile))
        {
            InternalLogger.Debug("Attempting to load config from {0}", configFile);
            _config = new XmlLoggingConfiguration(configFile);
        }
        else
        {
            InternalLogger.Warn("NLog global config file pointed by NLOG_GLOBAL_CONFIG '{0}' doesn't exist.", configFile);
        }
    }
}

Since the code is commented no EnvironmentPermission will be thrown even if there is no explicit configuration provided. As a side effect you can’t rely on default configuration settings anymore but this shouldn’t be a big issue since you can’t read them in a default partially trusted environment anyway.

4. Compile in release configuration and there you go.

Don’t forget, most of the default logging targets won’t work due to the security permissions. But the ones your application has access to will.

Happy logging.

One thought on “Running NLog in WPF Browser Application and other partially trusted environments

  1. Miha,

    Thanks so much for posting this article. Saved me a lot of time and frustration.

    For other NLog users struggling with this, I also had to add [assembly: System.Security.AllowPartiallyTrustedCallers] to AssemblyBuildInfo.cs (Not sure if just adding it to AssemblyBuildInfo.cs would have sufficed since I have it in both Assembly files). Also, I had to turn off autoReload in NLog.config to remove new security errors that followed.

    Thanks again!

Leave a Reply