我正在使用NLog v4.4.12。
我有一个异步方法,我必须使用包含的行号记录信息。问题是,如果我在调用异步方法之前记录任何内容,则行lumber始终为0.但是,如果我在调用异步方法后记录任何内容,则行号始终正确打印。还有其他人有这个问题吗?
示例:
public class TestController : ApiController {
private static HttpClient Client = new HttpClient(new HttpClientHandler { Proxy = null, UseProxy = false })
{ Timeout = TimeSpan.FromSeconds(double.Parse(WebConfigurationManager.AppSettings["httpTimeout"])) };
private static readonly Logger logger = LogManager.GetCurrentClassLogger();
public async Task DoSomething(int clientId)
{
logger.Info($"Here, line number is always 0");
try
{
var clientBooks = new List<string>();
Client.DefaultRequestHeaders.Accept.Clear();
Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
using (var response = await Client.GetAsync(new Uri(WebConfigurationManager.AppSettings["cb"] + "books?clientId=" + clientId)))
{
if (response.IsSuccessStatusCode)
{
clientBooks = await response.Content.ReadAsAsync<List<string>>();
}
else
{
throw new Exception($"Error getting books");
}
}
logger.Info($"Here, line number always prints correctly");
// Here I have some other logic ...
}
catch (Exception ex)
{
logger.Error(ex);
}
logger.Info($"Here, line number always prints correctly");
}
}
我的NLog配置:
<nlog autoReload="true" xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<variable name="logDirectory" value="${basedir}/Logs/${shortdate}" />
<variable name="format" value="${longdate}|${activityid}|${logger}|${callsite-linenumber}|${level:uppercase=true}|${message}" />
<targets>
<target name="fileLogErrors" xsi:type="File" fileName="${logDirectory}/errors.txt" layout="${format}" encoding="utf-8" />
<target name="fileLog" xsi:type="File" fileName="${logDirectory}/all.txt" layout="${format}" encoding="utf-8" />
</targets>
<rules>
<logger name="*" minlevel="Warn" writeTo="fileLogErrors" />
<logger name="*" minlevel="Info" writeTo="fileLog" />
</rules>
</nlog>