log4net 快速使用demo

添加log4net包

log4net 快速使用demo_第1张图片

然后查找安装

log4net 快速使用demo_第2张图片

首先是在根目录下创建log4net.config 配置文件



  
    

其次 是设定工具类,只要是 info 以及 error

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace testlog4net
{
    public partial class LogUtils
    {
        public static void ErrorLog(object msg)
        {
            log4net.ILog log = log4net.LogManager.GetLogger("logerror");
            Task.Run(() => log.Error(msg));   //异步
        }

        public static void ErrorLog(Exception ex)
        {
            log4net.ILog log = log4net.LogManager.GetLogger("logerror");
            if (!(ex.Source is null))
            {
                Task.Run(() => log.Error(ex.Message.ToString() + "/r/n" + ex.Source.ToString() + "/r/n" + ex.TargetSite.ToString() + "/r/n" + ex.StackTrace.ToString()));
            }
            else
            {
                Task.Run(() => log.Error(ex.Message.ToString()));
            }
        }

        public static void ErrorLog(object msg, Exception ex)
        {
            log4net.ILog log = log4net.LogManager.GetLogger("logerror");

            if (!(ex.Source is null))
            {
                Task.Run(() => log.Error(msg.ToString() + "/r/n" + ex.Message.ToString()));
            }
            else
            {
                Task.Run(() => log.Error(msg.ToString() + "/r/n" + ex.Message.ToString() + "/r/n" + ex.Source.ToString() + "/r/n" + ex.TargetSite.ToString() + "/r/n" + ex.StackTrace.ToString()));
            }
        }

        public static void InfoLog(object msg)
        {
            log4net.ILog log = log4net.LogManager.GetLogger("loginfo");
            log.Info(msg);
        }
    }
}

然后在 properties的AssemblyInfo.cs中加入,不加的话不会报错,但是不会显示log

//log4net配置
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = false)]

再然后,设定log4net.config  配置到 debug目录中

log4net 快速使用demo_第3张图片

最后可以测试一下了

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace testlog4net
{
    class Program
    {
        static void Main(string[] args)
        {
            LogUtils.InfoLog("201912271709插入一条消息");
            try
            {
                int a = 1;
                int b = 0;
                int i = a / b;
            }
            catch (Exception e)
            {
                LogUtils.ErrorLog(e);
                //throw;
            }
            Console.WriteLine("已经执行LOG插入");
            Console.ReadKey();
        }
    }
}

 

你可能感兴趣的:(C#)