autofac注入log4net

參考:https://github.com/erangil2/autofac.log4net

           https://autofaccn.readthedocs.io/zh/latest/examples/log4net.html

1、日誌接口

/// <summary>
/// 日誌接口
/// </summary>
public interface IFMLog : ISingleton
{
	/// <summary>
	/// 輸出異常信息
	/// </summary>
	/// <param name="t"></param>
	/// <param name="e"></param>
	void WriteError(Type t, Exception e);

	/// <summary>
	/// 輸出普通錯誤信息
	/// </summary>
	/// <param name="ex"></param>
	void WriteError(Exception ex);

	/// <summary>
	/// 輸出DEBUG信息
	/// </summary>
	/// <param name="text"></param>
	void WriteDebug(string text);

	/// <summary>
	/// 輸出程序運行信息
	/// </summary>
	/// <param name="text"></param>
	void WriteInfo(string text);

	/// <summary>
	/// 輸出警告信息
	/// </summary>
	/// <param name="text"></param>
	void WriteWarn(string text);
}

 2、實現

/// <summary>
/// 日誌記錄
/// </summary>
public class FMLog : IFMLog
{
	private ILog log;

	public FMLog(ILog log)
	{
		this.log = log;
	}

	/// <summary>
	/// 輸出異常信息
	/// </summary>
	/// <param name="t"></param>
	/// <param name="e"></param>
	public void WriteError(Type t, Exception e)
	{
		RemoveHisLog();

		//log4net.ILog log = log4net.LogManager.GetLogger("ERROR");
		log.Error("Error", e);
		log.Error("\r\n");
	}

	/// <summary>
	/// 輸出普通錯誤信息
	/// </summary>
	/// <param name="ex"></param>
	public void WriteError(Exception ex)
	{
		RemoveHisLog();

		//log4net.ILog log = log4net.LogManager.GetLogger("ERROR");
		log.Error("Error", ex);
		log.Error("\r\n");
	}

	/// <summary>
	/// 輸出DEBUG信息
	/// </summary>
	/// <param name="text"></param>
	public void WriteDebug(string text)
	{
		RemoveHisLog();

		//log4net.ILog log = log4net.LogManager.GetLogger("DEBUG");
		log.Debug(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + text);
		log.Debug("\r\n");
	}

	/// <summary>
	/// 輸出程序運行信息
	/// </summary>
	/// <param name="text"></param>
	public void WriteInfo(string text)
	{
		RemoveHisLog();

		//IFMLog log = LogManager.GetLogger("INFO");
		log.Info(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + text);
		log.Info("\r\n");
	}

	/// <summary>
	/// 輸出警告信息
	/// </summary>
	/// <param name="text"></param>
	public void WriteWarn(string text)
	{
		RemoveHisLog();

		//IFMLog log = LogManager.GetLogger("WARN");
		log.Warn(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + text);
		log.Warn("\r\n");
	}

	/// <summary>
	/// 移除一個月前的日誌
	/// </summary>
	private void RemoveHisLog()
	{
		try
		{
			string path = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "Log");
			//創建路徑
			if (Directory.Exists(path))
			{
				string[] directories = Directory.GetDirectories(path);
				if (directories != null && directories.Length > 31)
				{
					// 刪除1個月以前的文件
					DateTime dt = DateTime.Now.AddMonths(-1);
					foreach (var directory in directories)
					{
						if (File.GetCreationTime(directory) < dt)
							Directory.Delete(directory, true);
					}
				}
			}
		}
		catch
		{

		}
	}
}

3、LogInjectionModule

/// <summary>
    /// 日誌模塊注入
    /// </summary>
    public class LogInjectionModule : Autofac.Module
    {
        private static void InjectLoggerProperties(object instance)
        {
            var instanceType = instance.GetType();

            // Get all the injectable properties to set.
            // If you wanted to ensure the properties were only UNSET properties,
            // here's where you'd do it.
            var properties = instanceType
              .GetProperties(BindingFlags.Public | BindingFlags.Instance)
              .Where(p => p.PropertyType == typeof(ILog) && p.CanWrite && p.GetIndexParameters().Length == 0);

            // Set the properties located.
            foreach (var propToSet in properties)
            {
                propToSet.SetValue(instance, LogManager.GetLogger(instanceType), null);
            }
        }

        private static void OnComponentPreparing(object sender, PreparingEventArgs e)
        {
            e.Parameters = e.Parameters.Union(
              new[]
              {
                new ResolvedParameter(
                    (p, i) => p.ParameterType == typeof(ILog),
                    (p, i) => LogManager.GetLogger(p.Member.DeclaringType)
                ),
              });
        }

        protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration)
        {
            // Handle constructor parameters.
            registration.Preparing += OnComponentPreparing;

            // Handle properties.
            registration.Activated += (sender, e) => InjectLoggerProperties(e.Instance);
        }
    }
}

4、注入

var builder = new ContainerBuilder();

//  註冊日誌
// 使用上面建的注入類
//builder.RegisterModule(new LogInjectionModule());
// 安裝Autofac.log4net包後再注入
builder.RegisterModule<Log4NetModule>();
builder.RegisterType<FMLog>().As<IFMLog>().SingleInstance();

5、調用

System.IO.FileInfo fileInfo = new System.IO.FileInfo(System.AppDomain.CurrentDomain.BaseDirectory + "\\Configs\\log4net.config");
log4net.Config.XmlConfigurator.ConfigureAndWatch(fileInfo);

//顯示Autofac注入
IocManager.Instance.Builder();

var log = IocManager.Instance.Container.Resolve<IFMLog>();
log.WriteDebug("123");
log.WriteInfo("4556");

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章