示例: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("點擊登錄");

爲寫日誌方法;

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章