前言

之前.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;
}
}
}
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;
}
}
}

在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(); }

新建一个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();
}
}
}
}
}

新建控制器测试

        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文件上右键——属性——将“复制到输出目录”项的值改为“如果较新则复制”即可。

  

.net core 自制错误日志的更多相关文章

  1. .Net Core中间件和过滤器实现错误日志记录

    1.中间件的概念 ASP.NET Core的处理流程是一个管道,中间件是组装到应用程序管道中用来处理请求和响应的组件. 每个中间件可以: 选择是否将请求传递给管道中的下一个组件. 可以在调用管道中的下 ...

  2. 解决Apache的错误日志巨大的问题以及关闭Apache web日志记录

    调整错误日志的级别 这几天 apache错误日志巨大 莫名其妙的30G  而且 很多都是那种页面不存在的  网站太多了  死链接相应的也很多于是把错误警告调低了 因为写日志会给系统带来很大的损耗.关闭 ...

  3. centos7下,解决Apache错误日志文件过大问题

    1,日志文件太大问题   第一步:停止Apache服务的所有进程,删除 /var/log/httpd目录下的 error.log.access.log文件 第二步:打开 /etc/httpd/conf ...

  4. ASP.NET Core 异常处理与日志记录

    1. ASP.NET Core 异常处理与日志记录 1.1. 异常处理 1.1.1. 异常产生的原因及处理 1.1.2. ASP.NET Core中启动开发人员异常页面 1.2. 日志记录 1.2.1 ...

  5. 玩转ASP.NET Core中的日志组件

    简介 日志组件,作为程序员使用频率最高的组件,给程序员开发调试程序提供了必要的信息.ASP.NET Core中内置了一个通用日志接口ILogger,并实现了多种内置的日志提供器,例如 Console ...

  6. asp.net core 系列 13 日志

    一.概述 ASP.NET Core 支持适用于各种内置和第三方日志记录, 供程序的日志记录 API,本文介绍了如何将日志记录 API 与内置提供程序一起使用.对于第三方日志记录提供程序使用,文章最后有 ...

  7. WebForm应用log4net记录错误日志——使用线程列队写入

    我的项目结构如下图: 日志帮助类库需要log4net包:工具—NuGet包管理器—管理解决方案NuGet程序包 线程日志帮助类 FlashLogger.cs 代码 using System; usin ...

  8. Nginx错误日志与优化专题

    一.Nginx配置和内核优化 实现突破十万并发 二.一次Nignx的502页面的错误记录 (1)错误页面显示 错误日志: // :: [error] #: * recv() failed (: Con ...

  9. php源码建博客5--建库建表-配置文件-错误日志

    主要: 整理框架 建库建表 配置文件类 错误日志记录 --------------本篇后文件结构:-------------------------------------- blog ├─App │ ...

随机推荐

  1. Ubuntu 安装VNC

    ubuntu:.安装x11vnc sudo apt-get install x11vnc .设置密码 x11vnc -storepasswd .启动x11vnc(每次windows远程控制,都需要启动 ...

  2. DevExpress之XtraReport 学习

    XtraReport 一.基本概念: XtraReports 中的每个报表都由 XtraRepot 类的一个实例表示,或者由该类的子类来表示(这种情况更常见). 因此,每个报表都作为带区的容器使用,而 ...

  3. javax.persistence.RollbackException: Error while committing the transaction

    the valid jpa update entity code gives the exception below in the case of  wrong dependency( org.hib ...

  4. 【326】PIL 截图及图片识别

    参考:另一种用python识别图片文字的方法 参考:Python人工智能之图片识别,Python3一行代码实现图片文字识别 参考:Python3+Selenium3环境构建填坑之旅 参考:基于pyth ...

  5. SSH中将hibernate托管给spring获取session的方法

    import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionF ...

  6. So you've been rejected, now what? On appeals in peer-reviewed publications(From Wiley Exchanges)

    Getting rejected stinks. Wouldn’t it be great if we could appeal people’s decisions in life? Imagine ...

  7. 08-SSH综合案例:前台用户模块:注册页面的前台JS校验

    这个是MyEclipse设置的问题 把设置去掉就没问题了. 你也可以在每一个input后面加个span来显示提示的信息.这些东西也要提交到后台,后台也是要对这些东西进行校验的.

  8. 20172325《Java程序设计》第一周学习总结

    20172325<Java程序设计>第一周学习总结 教材学习内容总结 第一章 1.1软件质量 软件工程是一门关于高质量软件开发的技术和理论的学科. 高质量软件的特征 1.2 数据结构 软件 ...

  9. gnuc与ansic

    GNU c与标准c的区别 1) 零长度数组 struct var_data { int len; char data[0]; }test: int a; test.data -->a 2)cas ...

  10. [Java] Java API文档下载方法

    Java API文档下载方法:http://jingyan.baidu.com/article/a3aad71ac9e48fb1fb009692.html Oracle : http://www.or ...