简体   繁体   中英

How to have single log4net dll in multi layered application

I have a separate project for logging in my web api solution. In logging project i am using log4net dll. Its all working fine.

Looks like i have to add log4net dll in my web api project as well which is the entry point of my application.

1)Why do i need to add log4net dll in my web api project?

2)Is there any way to make this work without adding log4net in web api project? I like to use my logger peoject in different applications and don't want to have log4net in multiple projects.

 public class Logger : ILogger
 {
    private static readonly ILog LoggerObj = LogManager.GetLogger("ErrorLog");

    public Logger()
    {
        XmlConfigurator.Configure();
    }
 }

Global.asax

        protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        UnityConfig.RegisterComponents();
        GlobalConfiguration.Configure(WebApiConfig.Register);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

        // Initialize log4net.
        //log4net.Config.XmlConfigurator.Configure();

        // Initialize log4net.
        var logger = new Logger();
    }

The only way I see this is to add your Logging project as a reference to your web api project or any other project you would like to make use of Logging. On your Web Api project, right click on References -> Add References. Under Project -> Solution select you Logging project and click OK.

Edit:

Have a look at my implementation. I did in a separate project and followed the above steps to link to other projects.

namespace MyProject.Logger {
public partial class Log {

    private static readonly Log _instance = new Log();
    protected ILog monitoringLogger;
    protected static ILog debugLogger;

    private Log() {
        monitoringLogger = LogManager.GetLogger(System.Environment.MachineName);
        debugLogger = LogManager.GetLogger(System.Environment.MachineName);
    }

    public static void Debug(string message) {
        debugLogger.Debug(message);
    }

    public static void Debug(string message, Exception exception) {
        debugLogger.Debug(message, exception);
    }

    public static void Info(string message) {
        _instance.monitoringLogger.Info(message);
    }
}

Hope it helps

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