示例:AspNetCore 2.2 MVC 注入日志

2024-05-26 16:48

本文主要是介绍示例:AspNetCore 2.2 MVC 注入日志,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、目的:了解Asp.net Core MVC中添加日志模块的过程

 

二、过程:

 

1、添加Logging.json到应用程序集中

{"Logging": {"LogLevel": {"Default": "Debug","System": "Information","Microsoft": "Information"},"Console":{"IncludeScopes": "true","TimestampFormat": "[HH:mm:ss] ","LogToStandardErrorThreshold": "Warning"}}

2、在Startup中代码如下

  public class Startup{ILogger _logger;public Startup(IConfiguration configuration, ILogger<Startup> logger){Configuration = configuration;_logger = logger;}public IConfiguration Configuration { get; }// This method gets called by the runtime. Use this method to add services to the container.public void ConfigureServices(IServiceCollection services){_logger.LogInformation("Step ConfigureServices");//  Do:获取数据库连接字符串string cs = this.Configuration.GetConnectionString("MySqlConnection");//  Do:注册数据上下文services.AddDbContextWithConnectString<DataContext>(cs); //  Do:依赖注入services.AddScoped<IUserAccountRespositroy, UserAccountRespositroy>();//  Message:注册内服务领域模型//services.AddScoped<TestService>();//services.AddTransient(l => new HomeControler(new TestServer("fdfdd"))); 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.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);//  Message:注册过滤器//services.AddMvc(l=>l.Filters.Add(new SamepleGlobalActionFilter())) ;//  Do:注册日志var loggingConfiguration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("logging.json", optional: false, reloadOnChange: true).Build();services.AddLogging(builder =>{builder.AddConfiguration(loggingConfiguration.GetSection("Logging")).AddFilter("Microsoft", LogLevel.Warning).AddFilter("HeBianGu.Product.WebApp.Demo", LogLevel.Debug).AddConsole();}); }// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.public void Configure(IApplicationBuilder app, IHostingEnvironment env){//  Do:注册日志if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}else{app.UseExceptionHandler("/Home/Error");// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.app.UseHsts();}app.UseHttpsRedirection();app.UseStaticFiles();//app.UseCookiePolicy();app.UseMvc(routes =>{routes.MapRoute(name: "default",template: "{controller=Home}/{action=Login}/{id?}"); });//app.UseMvc(routes =>//{//    routes.MapRoute(//        name: "default",//        template: "{controller=User}/{action=Index}/{id?}");//});}}

其中,

//  Do:注册日志
            var loggingConfiguration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("logging.json", optional: false, reloadOnChange: true)
                .Build();

            services.AddLogging(builder =>
            {
                builder
                    .AddConfiguration(loggingConfiguration.GetSection("Logging"))
                    .AddFilter("Microsoft", LogLevel.Warning)
                    .AddFilter("HeBianGu.Product.WebApp.Demo", LogLevel.Debug)
                    .AddConsole();
            }); 

部分为注册日志的代码

 

3、在Controler中应用注入日志

  public class HomeController : Controller{IUserAccountRespositroy _respository;ILogger _logger;public HomeController(IUserAccountRespositroy respository, ILogger<HomeController> logger){_respository = respository;_logger = logger;}public IActionResult Index(){return View();}public IActionResult Privacy(){return View();}public IActionResult Login(){return View();}[HttpPost]public IActionResult Login(LoginViewModel model){_logger.LogInformation("点击登录");if (ModelState.IsValid){//检查用户信息var user = _respository.CheckUserLogin(model.UserName, model.Password);if (user != null){//记录Session//HttpContext.Session.SetString("CurrentUserId", user.Id.ToString());//HttpContext.Session.Set("CurrentUser", ByteConvertHelper.Object2Bytes(user));//跳转到系统首页return RedirectToAction("Monitor", "Monitor");}ViewBag.ErrorInfo = "用户名或密码错误。";return View();}foreach (var item in ModelState.Values){if (item.Errors.Count > 0){ViewBag.ErrorInfo = item.Errors[0].ErrorMessage;break;}}return View();}[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]public IActionResult Error(){return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });}//  Message:每个控制器的基类Controler 都包含两个过滤器,这个在过滤器之后调用,下面在过滤器之前调用public override void OnActionExecuted(ActionExecutedContext context){Debug.WriteLine("OnActionExecuted");base.OnActionExecuted(context);}public override void OnActionExecuting(ActionExecutingContext context){Debug.WriteLine("OnActionExecuting");base.OnActionExecuting(context);}}

其中,

ILogger _logger;

        public HomeController(IUserAccountRespositroy respository, ILogger<HomeController> logger)
        {
            _respository = respository;

            _logger = logger;
        }

部分为获取日志方法;

_logger.LogInformation("点击登录");

为写日志方法;

 

 

 

这篇关于示例:AspNetCore 2.2 MVC 注入日志的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1005036

相关文章

Python函数作用域示例详解

《Python函数作用域示例详解》本文介绍了Python中的LEGB作用域规则,详细解析了变量查找的四个层级,通过具体代码示例,展示了各层级的变量访问规则和特性,对python函数作用域相关知识感兴趣... 目录一、LEGB 规则二、作用域实例2.1 局部作用域(Local)2.2 闭包作用域(Enclos

怎样通过分析GC日志来定位Java进程的内存问题

《怎样通过分析GC日志来定位Java进程的内存问题》:本文主要介绍怎样通过分析GC日志来定位Java进程的内存问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、GC 日志基础配置1. 启用详细 GC 日志2. 不同收集器的日志格式二、关键指标与分析维度1.

解读GC日志中的各项指标用法

《解读GC日志中的各项指标用法》:本文主要介绍GC日志中的各项指标用法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、基础 GC 日志格式(以 G1 为例)1. Minor GC 日志2. Full GC 日志二、关键指标解析1. GC 类型与触发原因2. 堆

C++20管道运算符的实现示例

《C++20管道运算符的实现示例》本文简要介绍C++20管道运算符的使用与实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录标准库的管道运算符使用自己实现类似的管道运算符我们不打算介绍太多,因为它实际属于c++20最为重要的

Java中调用数据库存储过程的示例代码

《Java中调用数据库存储过程的示例代码》本文介绍Java通过JDBC调用数据库存储过程的方法,涵盖参数类型、执行步骤及数据库差异,需注意异常处理与资源管理,以优化性能并实现复杂业务逻辑,感兴趣的朋友... 目录一、存储过程概述二、Java调用存储过程的基本javascript步骤三、Java调用存储过程示

ModelMapper基本使用和常见场景示例详解

《ModelMapper基本使用和常见场景示例详解》ModelMapper是Java对象映射库,支持自动映射、自定义规则、集合转换及高级配置(如匹配策略、转换器),可集成SpringBoot,减少样板... 目录1. 添加依赖2. 基本用法示例:简单对象映射3. 自定义映射规则4. 集合映射5. 高级配置匹

C++11作用域枚举(Scoped Enums)的实现示例

《C++11作用域枚举(ScopedEnums)的实现示例》枚举类型是一种非常实用的工具,C++11标准引入了作用域枚举,也称为强类型枚举,本文主要介绍了C++11作用域枚举(ScopedEnums... 目录一、引言二、传统枚举类型的局限性2.1 命名空间污染2.2 整型提升问题2.3 类型转换问题三、C

Java实现自定义table宽高的示例代码

《Java实现自定义table宽高的示例代码》在桌面应用、管理系统乃至报表工具中,表格(JTable)作为最常用的数据展示组件,不仅承载对数据的增删改查,还需要配合布局与视觉需求,而JavaSwing... 目录一、项目背景详细介绍二、项目需求详细介绍三、相关技术详细介绍四、实现思路详细介绍五、完整实现代码

C++ 检测文件大小和文件传输的方法示例详解

《C++检测文件大小和文件传输的方法示例详解》文章介绍了在C/C++中获取文件大小的三种方法,推荐使用stat()函数,并详细说明了如何设计一次性发送压缩包的结构体及传输流程,包含CRC校验和自动解... 目录检测文件的大小✅ 方法一:使用 stat() 函数(推荐)✅ 用法示例:✅ 方法二:使用 fsee

mysql查询使用_rowid虚拟列的示例

《mysql查询使用_rowid虚拟列的示例》MySQL中,_rowid是InnoDB虚拟列,用于无主键表的行ID查询,若存在主键或唯一列,则指向其,否则使用隐藏ID(不稳定),推荐使用ROW_NUM... 目录1. 基本查询(适用于没有主键的表)2. 检查表是否支持 _rowid3. 注意事项4. 最佳实