简体   繁体   中英

How to set Quartz.net worker thread name?

How can I set name of the worker thread in Quartz.net?

[2009-12-15 08:56:25] [DefaultQuartzScheduler_Worker-1] INFO

I wanted to see some meaningful information in the logs. I tried using JobDetail constructor, but looks like I am wrong.

var job = new JobDetail("n1", null, typeof (MyJob));

Atleast there is no way to set the name of the worker thread. However, I have used %property facility of log4net to produce meaningful thread name in log files

This is a new answer to an old question, but maybe its helpful to someone.

I didn't like the long quartz thread name [DefaultQuartzScheduler_Worker-1] in my log files.

Instead I wanted log4net to show the thread id. Therefor you need to set a property that logs the current thread's id.

I found this class. source
This is a lambda / func way of logging calculated context: log4net context explained

public class Log4NetContextProperty : IFixingRequired
{
    private readonly Func<string> _getValue;

    public Log4NetContextProperty(Func<string> getValue)
    {
        _getValue = getValue;
    }

    public override string ToString()
    {
        return _getValue();
    }

    public object GetFixedObject()
    {
        return ToString();
    }
}

And you have to call it this way in your application start place.

log4net.GlobalContext.Properties["threadId"] = new Log4NetContextProperty(() => Thread.CurrentThread.ManagedThreadId.ToString());

Then in your log4net config adapt the conversionpattern to include the new property. Mine looks like this:

<conversionPattern value="%d{dd.MM.yyyy HH:mm:ss,ffff} %-5level [%property{threadId}] - %message%newline" />

That's it. This way the id of each thread will be determinded at runtime and logged in its own property.

Usually you would be interested in what jobs output (they should have their own loggers) and not interested in the thread.

Do you have a specific case where you need logical names for threads? The threads are pooled and there are no guarantees about which thread gets what kind of job to to process. That's why the thread name usually is usable only for debug purposes to track the things happened in specific thread's life-cycle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM