NLog how to use Isolated LogFactories with a custom logger class - c#

I ran into a issue because LogManager is global, so my two projects were overriding each other's logging config. NLog log calls in the first project would work fine, but then when calling into the second project, all future log calls would be logged with the second projects config.
Example:
Target 1 "First log in first project" (supposed to be target 1)
Target 2 "Second log in second project" (supposed to be target 2)
Target 2 "Third log in first project" (supposed to be target 1)
I found Isolated logfactory which solved my issue, now the loggers has the correct config. However I cannot figure out how to use my custom NLog class with this method of making LogFactories.
This works great (but doesn't let me use my custom class with methods):
private static Logger logger = MyLogger.MyLogManager.Instance.GetCurrentClassLogger();
This:
private static MyLogger logger = (MyLogger)MyLogger.MyLogManager.Instance.GetCurrentClassLogger();
Throws:
System.TypeInitializationException: 'The type initializer for 'MyProject.MyClass.MyMethod' threw an exception.'
InvalidCastException: Unable to cast object of type 'NLog.Logger' to type 'MyProject.NLogConfigFolder.MyLogger'.
I have tried to cast Logger to MyLogger but have not been able to do so successfully.
Here is my setup for the isolated LogFactory:
public class MyLogger : Logger
{
public class MyLogManager
{
public static LogFactory Instance { get { return _instance.Value; } }
private static Lazy<LogFactory> _instance = new Lazy<LogFactory>(BuildLogFactory);
private static LogFactory BuildLogFactory()
{
string configFilePath = "path/to/my/config"
LogFactory logFactory = new LogFactory();
logFactory.Configuration = new XmlLoggingConfiguration(configFilePath, true, logFactory);
return logFactory;
}
}
// Other methods here
}
Thank you for your time and help with this problem.

Think you just need to change:
(MyLogger)MyLogger.MyLogManager.Instance.GetCurrentClassLogger()
Into this:
MyLogger.MyLogManager.Instance.GetCurrentClassLogger<MyLogger>()
See also: https://nlog-project.org/documentation/v5.0.0/html/Overload_NLog_LogFactory_GetCurrentClassLogger.htm

Related

The call is ambiguous between the following methods or properties?

Currently, I am working on an old project and I met too many errors, my goal is to succeed the deployment on my local machine, Brief in this below class, the GetHelpPageSampleGenerator() is underlined in red:
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
In the same classe i have the method GetHelpPageSampleGenerator() but overload, it means that the method SetSampleObjects and by using config argument which i can't understand it calls GetHelpPageSampleGenerator() :
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
the error that i get:
Severity Code Description Project File Line Suppression State
Error CS0121 The call is ambiguous between the following methods or
properties:
'WebInstructionSheet.Areas.HelpPage.HelpPageConfigurationExtensions.GetHelpPageSampleGenerator(System.Web.Http.HttpConfiguration)'
and
'WebInstructionSheet.Areas.HelpPage.HelpPageConfigurationExtensions.GetHelpPageSampleGenerator(System.Web.Http.HttpConfiguration)'

How do I provide ILogger<T> in my unit tests of .NET Core code?

Given a class with a constructor signature of
public Foo(ILogger<Foo> logger) {
// ...
}
that I want to test, I need some way to provide an ILogger<Foo> in the test. It's been asked before, but the only answer then was to set up a full-blown service registry, configure logging and resolve the logger from there. This seems very overkill to me.
Is there a simple way to provide an implementation of ILogger<T> for testing purposes?
Note: it doesn't have to actually log anything - just not blow up when the subject under test tries to log something.
Starting from dotnet core 2.0 there's a generic NullLogger<T> class available:
var foo = new Foo(NullLogger<Foo>.Instance);
https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.abstractions.nulllogger-1?view=aspnetcore-2.1 (docs)
https://github.com/aspnet/Logging/blob/master/src/Microsoft.Extensions.Logging.Abstractions/NullLoggerOfT.cs (source)
Or if you need it as part of your services:
services.AddSingleton<ILoggerFactory, NullLoggerFactory>();
https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.abstractions.nullloggerfactory?view=aspnetcore-2.1 (docs)
You can create an instance of ILogger<Foo> using NullLoggerFactory as the factory.
Consider the following controller:
public abstract class Foo: Controller
{
public Foo(ILogger<Foo> logger) {
Logger = logger;
}
public ILogger Logger { get; private set; }
}
A sample unit test could be:
[TestMethod]
public void FooConstructorUnitTest()
{
// Arrange
ILogger<FooController> logger = new Logger<FooController>(new NullLoggerFactory());
// Act
FooController target = new FooController(logger);
// Assert
Assert.AreSame(logger, target.Logger);
}
If you use generic logger (ILogger<>) in your classes those instances are generated from IServiceProvider you should register generic NullLogger<> on service provider as below. Not important what you use generic type T in ILogger<>
services.AddSingleton(typeof(ILogger<>), typeof(NullLogger<>));
You have two options:
Create empty implementation of ILogger<Foo> by hand and pass an instance of it to ctor.
Create same empty implementation on the fly using some mocking framework like Moq, NSubstitute, etc.
You could inject ILoggerFactory instead and then create the logger
public Foo(ILoggerFactory loggerFactory) {
logger = loggerFactory.CreateLogger<Foo>();
// ...
}
At startup you need to add the NullLoggerFactory service of course:
services.AddSingleton<ILoggerFactory, NullLoggerFactory>()
From the docs for ILogger<T> (emphasis mine):
A generic interface for logging where the category name is derived from the specified TCategoryName type name. Generally used to enable activation of a named ILogger from dependency injection.
So one option would be to change the implementation of the Foo method to take a plain ILogger and use the NullLogger implementation.
You should use the Null Object Pattern. This has two advantages for you: 1) you can get your tests up and running quickly and they won't "blow up", and 2) anyone will be able to use your class without supplying a logger. Just use NullLogger.Instance, or NullLoggerFactory.Instance.
However, you should use a mocking framework to verify that log calls get made. Here is some sample code with Moq.
[TestMethod]
public void TestLogError()
{
var recordId = new Guid("0b88ae00-7889-414a-aa26-18f206470001");
_logTest.ProcessWithException(recordId);
_loggerMock.Verify
(
l => l.Log
(
//Check the severity level
LogLevel.Error,
//This may or may not be relevant to your scenario
It.IsAny<EventId>(),
//This is the magical Moq code that exposes internal log processing from the extension methods
It.Is<It.IsAnyType>((state, t) =>
//This confirms that the correct log message was sent to the logger. {OriginalFormat} should match the value passed to the logger
//Note: messages should be retrieved from a service that will probably store the strings in a resource file
CheckValue(state, LogTest.ErrorMessage, "{OriginalFormat}") &&
//This confirms that an argument with a key of "recordId" was sent with the correct value
//In Application Insights, this will turn up in Custom Dimensions
CheckValue(state, recordId, nameof(recordId))
),
//Confirm the exception type
It.IsAny<NotImplementedException>(),
//Accept any valid Func here. The Func is specified by the extension methods
(Func<It.IsAnyType, Exception, string>)It.IsAny<object>()),
//Make sure the message was logged the correct number of times
Times.Exactly(1)
);
}
private static bool CheckValue(object state, object expectedValue, string key)
{
var keyValuePairList = (IReadOnlyList<KeyValuePair<string, object>>)state;
var actualValue = keyValuePairList.First(kvp => string.Compare(kvp.Key, key, StringComparison.Ordinal) == 0).Value;
return expectedValue.Equals(actualValue);
}
For more context, see this article.
If you need to verify the calls in addition to just provide the instance, it gets somewhat complicated. The reason is that most calls does not actually belong to the ILogger interface itself.
I have written a more detailed answer here.
Here is a small overview.
Example of a method that I have made to work with NSubstitute:
public static class LoggerTestingExtensions
{
public static void LogError(this ILogger logger, string message)
{
logger.Log(
LogLevel.Error,
0,
Arg.Is<FormattedLogValues>(v => v.ToString() == message),
Arg.Any<Exception>(),
Arg.Any<Func<object, Exception, string>>());
}
}
And this is how it can be used:
_logger.Received(1).LogError("Something bad happened");
You should try this for mocking ILogger:
mock.Setup(m => m.Log<object>(It.IsAny<LogLevel>(),It.IsAny<EventId>(),It.IsAny<object>(),It.IsAny<Exception>(),It.IsAny<Func<object, Exception,string>>()))
.Callback<LogLevel, EventId, object, Exception, Func<object, Exception, string>>((logLevel, eventId, obj, exception, func) =>
{
string msg = func.Invoke(obj, exception);
Console.WriteLine(msg);
});
This worked for me:
private FooController _fooController;
private Mock<ILogger<FooController>> _logger;
[TestInitialize]
public void Setup()
{
_logger = new Mock<ILogger<FooController>>();
_fooController = new FooController(_logger.Object);
}

can I pass a custom property to NLOG and output to file?

EDIT 4: "From" seems to be a reserved word in NLog. Changing it "FromID" worked. this is an awesome way to pass variables to NLog and still keep your code clean !!!! THANK MIKE!!!
EDIT 3. I really like this idea.:
Implemented a helper class as Mike suggested below:
public class NLogHelper
{
//
// Class Properties
//
private Logger m_logger;
private Dictionary<string, object> m_properties;
//
// Constructor
//
public NLogHelper(Logger logger)
{
m_logger = logger;
m_properties = new Dictionary<string, object>();
}
//
// Setting Logger properties per instancce
//
public void Set(string key, object value)
{
m_properties.Add(key, value);
}
//
// Loggers
//
public void Debug(string format, params object[] args)
{
m_logger.Debug()
.Message(format, args)
.Properties(m_properties)
.Write();
}
and in my main code, I have:
private NLogHelper m_logger;
public void Start()
{
m_logger = new NLogHelper(LogManager.GetCurrentClassLogger());
m_logger.Set("From", "QRT123"); // Class setting.
m_logger.Debug("Hello ");
}
And the target set in the config file as follows:
<target xsi:type="File"
name ="LogFile" fileName="C:\QRT\Logs\QRTLog-${shortdate}.log"
layout ="${date}|${level}|${event-properties:item=From}|${message} "/>
But the output has a BLANK in the place of the 'from' property ???
So I'm ALMOST THERE... but it does not seem to work??
EDIT 2:
I am now trying to create my own version of the NLog call:
private void Log_Debug (string Message)
{
LogEventInfo theEvent = new LogEventInfo(LogLevel.Debug, "What is this?", Message);
theEvent.Properties["EmployeeID"] = m_employeeID;
m_logger.Log(theEvent);
}
The issue is that I have to format the string for the calls (but a huge performance deal)... but this seems like a hack??
Ideally, I would declare properties in the custom layout renderer and instead of setting those properties in the configuration file, each instance of my class would have the property set... something like [ID = m_ID] for the whole class. This way whenever a NLog is called from that class, the ID property is set and NLog's custom layout renderer can use this property to output it. Am I making sense??
I'm new to NLog and have been looking at custom renderers.
Basically, my goal is to have my log statements be:
_logger.Debug ("My Name is {0}", "Ed", ID=87);
and I'd like my rendered to be something like:
layout = ${ID} ${date} ${Level} ${Message}
That's it. ${ID} can have a default value of 0. fine. But ideally, I'd like every call to have the ability to specify an ID without needing to have 3 lines everytime I want to log.
I've seen custom renderers allowing me to customize what I output but i'm not sure how I can customize the properties I pass to it without
https://github.com/NLog/NLog/wiki/Extending%20NLog shows how I can add properties but I don't know how to call them.
Also, https://github.com/NLog/NLog/wiki/Event-Context-Layout-Renderer shows how I can set custom properties but that involved the creation of a LogEventInfo object every time I want to log something.
Nlog Custom layoutrenderer shows how to customize the output.. again... not how to customize the inputs.
This is for a Console app in C# targeting .NET 4.0 using VS2013
Thanks
-Ed
Event properties (used to be called event-context) would be the built-in way to do what you want. If you are using NLog 3.2+ you can use the fluent api, which may be a bit more appealing than creating LogEventInfo objects. You can access this api by by using the namespace NLog.Fluent.
Your layout would then be defined like this:
${event-properties:item=ID} ${date} ${Level} ${Message}
Then using the fluent api, log like this:
_logger.Debug()
.Message("My name is {0}", "Ed")
.Property("ID", 87)
.Write();
Other than setting properties per event as above, the only other option would be to set properties per thread using MDC or MDLS.
NLog dosen't have a way (that I have found) of setting per-logger properties. Internally, NLog caches Logger instances by logger name, but does not guarantee that the same instance of Logger will always be returned for a given logger name. So for example if you call LogManager.GetCurrentClassLogger() in the constructor of your class, most of the time you will get back the same instance of Logger for all instances of your class. In which case, you would not be able to have separate values on your logger, per instance of your class.
Perhaps you could create a logging helper class that you can instantiate in your class. The helper class can be initialized with per-instance property values to be logged with every message. The helper class would also provide convenience methods to log messages as above, but with one line of code. Something like this:
// Example of a class that needs to use logging
public class MyClass
{
private LoggerHelper _logger;
public MyClass(int id)
{
_logger = new LoggerHelper(LogManager.GetCurrentClassLogger());
// Per-instance values
_logger.Set("ID", id);
}
public void DoStuff()
{
_logger.Debug("My name is {0}", "Ed");
}
}
// Example of a "stateful" logger
public class LoggerHelper
{
private Logger _logger;
private Dictionary<string, object> _properties;
public LoggerHelper(Logger logger)
{
_logger = logger;
_properties = new Dictionary<string, object>();
}
public void Set(string key, object value)
{
_properties.Add(key, value);
}
public void Debug(string format, params object[] args)
{
_logger.Debug()
.Message(format, args)
.Properties(_properties)
.Write();
}
}
This would work with the same layout as above.
NLog 4.5 supports structured logging using message templates:
logger.Info("Logon by {user} from {ip_address}", "Kenny", "127.0.0.1");
See also https://github.com/NLog/NLog/wiki/How-to-use-structured-logging
See also https://github.com/NLog/NLog.Extensions.Logging/wiki/NLog-properties-with-Microsoft-Extension-Logging
Use MDLC Layout Renderer
MappedDiagnosticsLogicalContext.Set("PropertyName", "PropertyValue");
MappedDiagnosticsLogicalContext.Set("PropertyName2",
"AnotherPropertyValue");
In your nlog config:
${mdlc:item=PropertyName} ${mdlc:item=PropertyName2}
https://github.com/NLog/NLog/wiki/MDLC-Layout-Renderer
I had 6 variables I wanted to send to structured logging in multiple places (so when I get a user report I can search the log database on our key id fields). I created a logging scope class that leverages the MDLC. So it should be thread safe, work with async/await code and be 3 lines of code for 6 variables everywhere used.
public class MyClassLoggingScope : IDisposable
{
private readonly List<IDisposable> context;
public MyClassLoggingScope(MyClass varSource)
{
this.context = new List<IDisposable>
{
MappedDiagnosticsLogicalContext.SetScoped("Var1", varSource.Var1)
// list all scoped logging context variables
}
}
public void Dispose()
{
foreach (IDisposable disposable in this.context)
{
disposable.Dispose();
}
}
}
Usage:
using (new MyClassLoggingScope(this))
{
// do the things that may cause logging somewhere in the stack
}
Then as flux earlier suggested, in the logging config you can use ${mdlc:item=Var1}
This is propably not the best way to do this and not even thread safe but a quick and dirty solution: You could use Environment variables:
Environment.SetEnvironmentVariable("NLogOptionID", "87");
logger.Debug("My Name id Ed");
Environment.SetEnvironmentVariable("NLogOptionID", null);
In your layout, you can use environment variables.
${environment:variable=NLogOptionID}

Importing part from a different assembly

Approach
I am employing MEF to create a plugin-nable, if you will, application. My MEF host has an ILogger which exposes TraceMessage(string message). Class Logger implements ILogger and is decorated with an Export attribute so Logger looks like:
[Export(typeof (ILogger))]
public class Logger : ILogger
{ }
The idea being that the various plugins can be offered a central logger that they can write to. Thus, instantiation would be via [Import] attribue, for example:
[Export(typeof (ILogger))]
public class Logger : ILogger
{
private readonly IWindsorContainer _container;
public ICloudTrace CloudTrace
{
get { return _container.Resolve<ICloudTrace>(); }
}
public Logger()
{
_container = new WindsorContainer(new XmlInterpreter());
}
public void TraceMessage(string categoryName, string componentName, string message)
{
CloudTrace.TraceMessage(categoryName, componentName, message);
}
}
And subsequently a log message would be written via Logger.TraceMessage(string message).
Problem
However, this approach throws an InvalidOperationException in my host when its trying to resolve exports, with an error message Sequence contains no matching element.
Exports are resolved in ResolveType(string commandType) (where commandType is the command line parameter needed to execute relevant plugin). ResolveType() looks like:
public dynamic ResolveType(string commandType)
{
try
{
return this.Container.GetExports<ICommand, ICommandMetaData>()
.First(contract => contract.Metadata.CommandType.Equals(commandType, StringComparison.OrdinalIgnoreCase))
.Value;
}
catch (Exception e)
{
Console.WriteLine(e.message);
}
}
I should mention that each plugin has an Execute(Dictionary<string, string> parameters) which is the entry point for the plugin and the class containing this method is decorated with [Export(typeof(ICommand))] [ExportMetadata("CommandType","CommandLine Command string goes here")] attributes.
The problem was in the CompositionContainer construction. Currently, it just loads the plugin assembly specified in the command line instead of doing directory scan or loading currently executing assembly. This has been done for various reasons. So:
var assemblyCatalog = new AssemblyCatalog(Assembly.LoadFrom(assemblyFile: assemblyToLoad));
where assemblyToLoad is a string to the .dll file for the specific plugin. However, the logger is in the host so the host's assembly needs to be loaded. Thus:
var assemblyCatalog = new AggregateCatalog(new AssemblyCatalog(Assembly.GetExecutingAssembly()),
new AssemblyCatalog(Assembly.LoadFrom(assemblyFile: assemblyToLoad)));
fixes the issue.
Thanks to #Matthew Abbott for pointing this out

Is it possible to get the currently executing classname using reflection?

I'm writing a logging class and I would like to be able to get the name of the class that has the call to Helper.Log(string message).
Is this possible using reflection and c#?
Yes, it is quite easy.
Helper.Log("[" + this.GetType().Name + "]: " + message);
Note that if your logger class is really a wrapper around a logging framework (like log4net or NLog), the logging framework can be configured to get the calling class/method for you. For this to work correctly, you have to wrap the logging framework correctly. For NLog and log4net, correctly wrapping (to preserve call site information) generally involves using the "Log" method (rather than the Error, Warn, Info, etc variants) and passing the "logger type" as the first parameter. The "logger type" is the type of your logger that wraps the logging framework's logger.
Here is one way to wrap NLog (taken from here):
class MyLogger
{
private Logger _logger;
public MyLogger(string name)
{
_logger = LogManager.GetLogger(name);
}
public void WriteMessage(string message)
{
///
/// create log event from the passed message
///
LogEventInfo logEvent = new LogEventInfo(LogLevel.Info, _logger.Name, message);
// Call the Log() method. It is important to pass typeof(MyLogger) as the
// first parameter. If you don't, ${callsite} and other callstack-related
// layout renderers will not work properly.
//
_logger.Log(typeof(MyLogger), logEvent);
}
}
And here is how you could do it with log4net:
class MyLogger
{
private ILog _logger;
public MyLogger(string name)
{
_logger = LogManager.GetLogger(name);
}
public void WriteMessage(string message)
{
// Call the Log() method. It is important to pass typeof(MyLogger) as the
// first parameter. If you don't, ${callsite} and other callstack-related
// formatters will not work properly.
//
_logger.Log(typeof(MyLogger), LogLevel.Info, message);
}
}

Categories