Getting NLog Running in Partial Trust
To get things working you will need to:
Strong name sign the assembly
Allow Partially Trusted Callers
In the AssemblyInfo.cs file you will need to add the assembly attribute for “AllowPartiallyTrustedCallers”
You should now be able to get NLog working as part of a partial trust installation, except that the File target won’t work. Other targets will still work (database for example)
Changing BaseFileAppender.cs to get file logging to work
In the directory \Internal\FileAppenders there is a file called “BaseFileAppender.cs”.
Make a change to the function call “TryCreateFileStream()”. The error occurs here:
Change the function call to be:
private FileStream TryCreateFileStream(bool allowConcurrentWrite) { FileShare fileShare = FileShare.Read; if (allowConcurrentWrite) fileShare = FileShare.ReadWrite; #if DOTNET_2_0 if (_createParameters.EnableFileDelete && PlatformDetector.GetCurrentRuntimeOS() != RuntimeOS.Windows) { fileShare |= FileShare.Delete; } #endif #if !NETCF try { if (PlatformDetector.IsCurrentOSCompatibleWith(RuntimeOS.WindowsNT) || PlatformDetector.IsCurrentOSCompatibleWith(RuntimeOS.Windows)) { return WindowsCreateFile(FileName, allowConcurrentWrite); } } catch (System.Security.SecurityException secExc) { InternalLogger.Error("Security Exception Caught in WindowsCreateFile. {0}", secExc.Message); } #endif return new FileStream(FileName, FileMode.Append, FileAccess.Write, fileShare, _createParameters.BufferSize); }
Basically we wrap the call in a try..catch. If we catch a SecurityException when trying to create the FileStream using WindowsCreateFile(), we just swallow the exception and use the native System.Io.FileStream instead.