示例: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

相关文章

使用Java将各种数据写入Excel表格的操作示例

《使用Java将各种数据写入Excel表格的操作示例》在数据处理与管理领域,Excel凭借其强大的功能和广泛的应用,成为了数据存储与展示的重要工具,在Java开发过程中,常常需要将不同类型的数据,本文... 目录前言安装免费Java库1. 写入文本、或数值到 Excel单元格2. 写入数组到 Excel表格

Python中的Walrus运算符分析示例详解

《Python中的Walrus运算符分析示例详解》Python中的Walrus运算符(:=)是Python3.8引入的一个新特性,允许在表达式中同时赋值和返回值,它的核心作用是减少重复计算,提升代码简... 目录1. 在循环中避免重复计算2. 在条件判断中同时赋值变量3. 在列表推导式或字典推导式中简化逻辑

Python位移操作和位运算的实现示例

《Python位移操作和位运算的实现示例》本文主要介绍了Python位移操作和位运算的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 位移操作1.1 左移操作 (<<)1.2 右移操作 (>>)注意事项:2. 位运算2.1

IntelliJ IDEA 中配置 Spring MVC 环境的详细步骤及问题解决

《IntelliJIDEA中配置SpringMVC环境的详细步骤及问题解决》:本文主要介绍IntelliJIDEA中配置SpringMVC环境的详细步骤及问题解决,本文分步骤结合实例给大... 目录步骤 1:创建 Maven Web 项目步骤 2:添加 Spring MVC 依赖1、保存后执行2、将新的依赖

pandas中位数填充空值的实现示例

《pandas中位数填充空值的实现示例》中位数填充是一种简单而有效的方法,用于填充数据集中缺失的值,本文就来介绍一下pandas中位数填充空值的实现,具有一定的参考价值,感兴趣的可以了解一下... 目录什么是中位数填充?为什么选择中位数填充?示例数据结果分析完整代码总结在数据分析和机器学习过程中,处理缺失数

Pandas统计每行数据中的空值的方法示例

《Pandas统计每行数据中的空值的方法示例》处理缺失数据(NaN值)是一个非常常见的问题,本文主要介绍了Pandas统计每行数据中的空值的方法示例,具有一定的参考价值,感兴趣的可以了解一下... 目录什么是空值?为什么要统计空值?准备工作创建示例数据统计每行空值数量进一步分析www.chinasem.cn处

利用Python调试串口的示例代码

《利用Python调试串口的示例代码》在嵌入式开发、物联网设备调试过程中,串口通信是最基础的调试手段本文将带你用Python+ttkbootstrap打造一款高颜值、多功能的串口调试助手,需要的可以了... 目录概述:为什么需要专业的串口调试工具项目架构设计1.1 技术栈选型1.2 关键类说明1.3 线程模

Python使用getopt处理命令行参数示例解析(最佳实践)

《Python使用getopt处理命令行参数示例解析(最佳实践)》getopt模块是Python标准库中一个简单但强大的命令行参数处理工具,它特别适合那些需要快速实现基本命令行参数解析的场景,或者需要... 目录为什么需要处理命令行参数?getopt模块基础实际应用示例与其他参数处理方式的比较常见问http

Android实现在线预览office文档的示例详解

《Android实现在线预览office文档的示例详解》在移动端展示在线Office文档(如Word、Excel、PPT)是一项常见需求,这篇文章为大家重点介绍了两种方案的实现方法,希望对大家有一定的... 目录一、项目概述二、相关技术知识三、实现思路3.1 方案一:WebView + Office Onl

Mysql用户授权(GRANT)语法及示例解读

《Mysql用户授权(GRANT)语法及示例解读》:本文主要介绍Mysql用户授权(GRANT)语法及示例,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录mysql用户授权(GRANT)语法授予用户权限语法GRANT语句中的<权限类型>的使用WITH GRANT