当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - NLog performance

问题描述:

What should the expected overhead be for logging?

I have tried this example

 private class Person

{

private static Logger logger = LogManager.GetCurrentClassLogger();

public string Name { get; private set; }

public Person(string name)

{

Name = name;

logger.Info("New person created with name {0}", name);

}

}

List<Person> people = new List<Person>();

for (int i = 0; i < MAXTEST; i++)

{

people.Add(new Person(i.ToString()));

}

With MAXTEST values of 100,500,1000, 5000

Results in MAXTEST,noLogging, Logging

100, 25ms, 186ms

500, 33ms, 812ms

1000, 33ms, 1554ms

5000, 33ms, 7654ms

Granted one would probably never log this excessive amount, but it this the performance hit one would expect?

I have also tried using the asyncwrapper in the config

 <target name="asyncFile" xsi:type="AsyncWrapper">

<target name="file" xsi:type="File" fileName="${basedir}/log.txt" />

</target>

Regards

_Eric

网友答案:

You only need to add the async attribute to your targets element:

<targets async="true">
    <target name="asyncFile" xsi:type="AsyncWrapper">
        <target name="file" xsi:type="File" fileName="${basedir}/log.txt" />
    </target>

instead of

<targets>
    <target name="asyncFile" xsi:type="AsyncWrapper">
        <target name="file" xsi:type="File" fileName="${basedir}/log.txt" />
    </target>

I guess I didn't get that far into the documentation ;-)

Asynchronous target wrapper allows the logger code to execute more quickly, by queueing messages and processing them in a separate thread. You should wrap targets that spend a non-trivial amount of time in their Write() method with asynchronous target to speed up logging. Because asynchronous logging is quite a common scenario, NLog supports a shorthand notation for wrapping all targets with AsyncWrapper. Just add async="true" to the element in the configuration file. ... your targets go here ...

网友答案:

For anyone who needs to lose this overhead and is configuring by code, it doesn't look like you can set all targets to asynchronous by default - you have to define it per-target:

// Set up asynchronous database logging assuming dbTarget is your existing target
AsyncTargetWrapper asyncWrapper = new AsyncTargetWrapper(dbTarget);
config.AddTarget("async", asyncWrapper);

// Define rules
LoggingRule rule1 = new LoggingRule("*", LogLevel.Trace, asyncWrapper);
config.LoggingRules.Add(rule1);

Be wary that by default if you queue up too many log items it will just drop items - look at OverflowAction = AsyncTargetWrapperOverflowAction.Block to go back to synchronous behaviour.

分享给朋友:
您可能感兴趣的文章:
随机阅读: