.net core 自制错误日志

前言

 之前.net framework用的ErrorLog帮助类,对于监控错误形成日志,内容非常清晰,想在.net core2.2中继续用,但是有很多不一样的地方,所以想总结一下.

首先需要HttpContext,而.net core 与之前的.net framework有所不同,封装一下便于使用

建两个静态类 HttpContext  

using Microsoft.AspNetCore.Http;

namespace logs
{
    public static class HttpContext
    {
        private static IHttpContextAccessor _accessor;

        public static Microsoft.AspNetCore.Http.HttpContext Current => _accessor.HttpContext;

        internal static void Configure(IHttpContextAccessor accessor)
        {
            _accessor = accessor;
        }
    }
}
View Code
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace logs
{
    public static class StaticHttpContextExtensions
    {
        public static void AddHttpContextAccessor(this IServiceCollection services)
        {
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        }

        public static IApplicationBuilder UseStaticHttpContext(this IApplicationBuilder app)
        {
            var httpContextAccessor = app.ApplicationServices.GetRequiredService<IHttpContextAccessor>();
            HttpContext.Configure(httpContextAccessor);
            return app;
        }
    }
}
View Code

在Startup.cs中注入

 public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            //DI 注入
            services.AddHttpContextAccessor();
            
        }
View Code

新建一个ErrorLog类

using System;
using System.IO;

namespace logs
{
    public class ErrorLog
    {
        public static void WriteLog(Exception ex)
        {
            //读取二级
            var logsPath=AppConfigurtaionServices.Configuration["Path:LogsPath"];

            string errorTime = "异常时间:" + DateTime.Now.ToString();
            string errorAddress = "异常地址:" + HttpContext.Current.Request.Scheme.ToString()+"://"+ HttpContext.Current.Request.Host.ToString()+ HttpContext.Current.Request.Path.ToString();
            string errorInfo = "异常信息:" + ex.Message;
            string errorSource = "错误源:" + ex.Source;
            string errorType = "运行类型:" + ex.GetType();
            string errorFunction = "异常函数:" + ex.TargetSite;
            string errorTrace = "堆栈信息:" + ex.StackTrace;
         
            //HttpContext.Current.Server.ClearError();
            System.IO.StreamWriter writer = null;
            try
            {
                //写入日志 
                string path = string.Empty;
               path= System.AppDomain.CurrentDomain.BaseDirectory.ToString()+ logsPath;
                //path = HttpContext.Current.Server.MapPath("~/ErrorLogs/");
                //不存在则创建错误日志文件夹
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                path += string.Format(@"\{0}.txt", DateTime.Now.ToString("yyyy-MM-dd"));

                writer = !System.IO.File.Exists(path) ? System.IO.File.CreateText(path) : System.IO.File.AppendText(path); //判断文件是否存在,如果不存在则创建,存在则添加
                writer.WriteLine("用户IP:" + HttpContext.Current.Connection.RemoteIpAddress.ToString());
                writer.WriteLine(errorTime);
                writer.WriteLine(errorAddress);
                writer.WriteLine(errorInfo);
                writer.WriteLine(errorSource);
                writer.WriteLine(errorType);
                writer.WriteLine(errorFunction);
                writer.WriteLine(errorTrace);
                writer.WriteLine("********************************************************************************************");
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                }
            }
        }
    }
}
View Code

新建控制器测试

        public IActionResult Index()
        {
            try
            {
                var b = 0;
                int a = 10 / b;
            }
            catch (Exception ex)
            {

              ErrorLog.WriteLog(ex);
            }
            return View();
        }

  新建视图运行,在\bin\Debug\netcoreapp2.2\下创建logs文件夹与日期命名的txt文件  结果如下

 最后  安利一个特别棒的appsetting读取类

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

namespace logs
{
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.Configuration.Json;
    /// <summary>
    /// 读取appsetting.json
    /// </summary>
    public class AppConfigurtaionServices
    {
        public static IConfiguration Configuration { get; set; }
        static AppConfigurtaionServices()
        {
            //ReloadOnChange = true 当appsettings.json被修改时重新加载            
            Configuration = new ConfigurationBuilder()
            .Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true })
            .Build();
        }
    }
}
         //调用
        // AppConfigurtaionServices.Configuration.GetConnectionString("conn");
        //读取一级
        // AppConfigurtaionServices.Configuration["str"];
        //读取二级
        // AppConfigurtaionServices.Configuration["Path:LogsPath"];

        //注意,如果AppConfigurtaionServices类中抛出FileNotFoundException异常,说明目录下未找到appsettings.json文件,这时请在项目appsettings.json文件上右键——属性——将“复制到输出目录”项的值改为“如果较新则复制”即可。

  

猜你喜欢

转载自www.cnblogs.com/LiChen19951127/p/10475148.html