I have a class that programmatically creates a log using the Nlog framework. I have several processes running and creating their logs at the same time. I added a lock to the constructor of the class, as before the two threads were attempting to create a file at the same time which resulted in some annoying bugs (like only creating one log).
This seems to have solved that problem. However now i have the same issue with writing to the log, and using a lock has not helped. Here is the class.
public class CwiLogger
{
private Logger _log;
private static Object createLogLock = new Object();
private static Object writeLogLock = new Object();
public CwiLogger(string logPath, string logName, string className)
{
lock (createLogLock)
{
var config = new LoggingConfiguration();
var fileTarget = new FileTarget();
config.AddTarget("file", fileTarget);
fileTarget.FileName = Path.Combine(logPath, logName);
fileTarget.Layout = "${longdate}|${level:uppercase=true}|${logger}|${message}";
var rule = new LoggingRule("*", LogLevel.Debug, fileTarget);
config.LoggingRules.Add(rule);
LogManager.Configuration = config;
this._log = LogManager.GetLogger(className);
}
}
public void AddToLog(string logText, LogLevel level = null)
{
lock (writeLogLock)
{
level = level ?? LogLevel.Info;
this._log.Log(level, logText + "
");
}
}
}
In my client code i run two threads each running a process that looks like this:
var log = new CwiLogger(@"C:UsersjmaDocumentsProgrammingJunklogTest", "Log2.txt", "Log2");
for (int i = 0; i < 100; i++)
{
log.AddToLog("Log2 " + i);
}
only i use log1 for one and log2 for the other.
in my output. One of the 2 logs always sucessfully counts to 99, while the other gets 4-5 in and then has no other output.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…