當前位置: 首頁>>代碼示例>>C#>>正文


C# LoggerConfiguration.Error方法代碼示例

本文整理匯總了C#中Serilog.LoggerConfiguration.Error方法的典型用法代碼示例。如果您正苦於以下問題:C# LoggerConfiguration.Error方法的具體用法?C# LoggerConfiguration.Error怎麽用?C# LoggerConfiguration.Error使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在Serilog.LoggerConfiguration的用法示例。


在下文中一共展示了LoggerConfiguration.Error方法的12個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: Application_Error

        void Application_Error(object sender, EventArgs e)
        {
            var exception = Server.GetLastError();

            // Log the exception.
            using (var log = new LoggerConfiguration().ReadFrom.AppSettings().CreateLogger())
            {
                if (HttpContext.Current != null)
                    log.Error(exception, "Application_Error: an exception occurred at {0}", HttpContext.Current.Request.Url.ToString());
                else
                    log.Error(exception, "Application_Error: an exception occurred (but HttpContext.Current is null so the URL was not captured)");
            }
        }
開發者ID:txsll,項目名稱:SLLInvoices,代碼行數:13,代碼來源:Global.asax.cs

示例2: Run

 public static void Run()
 {
     var logger = new LoggerConfiguration()
     .WriteTo.MSSqlServer(@"Server=.;Database=LogEvents;Trusted_Connection=True;", "Logs")
     .CreateLogger();
     logger.Information("I am an information log");
     logger.Error("Hello, I am an error log");
 }
開發者ID:andyfengc,項目名稱:SerilogTutorial,代碼行數:8,代碼來源:DatabaseLogger.cs

示例3: Log

        public override void Log(ExceptionLoggerContext context)
        {
            using (var log = new LoggerConfiguration().ReadFrom.AppSettings().CreateLogger())
            {
                log.Error(context.Exception, "CustomExceptionLogger: An exception occurred in an API controller; see the log entry below for the request");
            }

            base.Log(context);
        }
開發者ID:txsll,項目名稱:SLLInvoices,代碼行數:9,代碼來源:CustomExceptionLogger.cs

示例4: Run

 public static void Run()
 {
     var logger = new LoggerConfiguration()
         .WriteTo.ColoredConsole()
         .WriteTo.RollingFile(@"D:\Log-{Date}.txt")
         .CreateLogger();
     var appointment =
         new { Id = 1, Subject = "Meeting of database migration", Timestamp = new DateTime(2015, 3, 12) };
     logger.Information("An appointment is booked successfully: {@appountment}", appointment);
     logger.Error("Failed to book an appointment: {@appountment}", appointment);
 }
開發者ID:andyfengc,項目名稱:SerilogTutorial,代碼行數:11,代碼來源:BasicLogger.cs

示例5: Main

        static void Main(string[] args)
        {
            var logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .WriteTo.ColoredConsole()
                .WriteTo.Elasticsearch("http://localhost:9200")
                .CreateLogger();

            logger.Information("Here is an informational message");
            logger.Debug("Some debug level info");
            logger.Error("And error level info");
        }
開發者ID:PyroJoke,項目名稱:LogPatterns,代碼行數:12,代碼來源:Program.cs

示例6: SetLevel

 public static void SetLevel()
 {
     var logger = new LoggerConfiguration()
      .MinimumLevel.Debug()
      .WriteTo.ColoredConsole()
      .CreateLogger();
     var appointment =
         new { Id = 1, Subject = "Meeting of database migration", Timestamp = new DateTime(2015, 3, 12) };
     logger.Verbose("You will not see this log");
     logger.Information("An appointment is booked successfully: {@appountment}", appointment);
     logger.Error("Failed to book an appointment: {@appountment}", appointment);
 }
開發者ID:andyfengc,項目名稱:SerilogTutorial,代碼行數:12,代碼來源:CustomizedLogger.cs

示例7: OnActionExecuting

        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (actionContext.ModelState.IsValid == false)
            {
                // Log the error.
                using (var log = new LoggerConfiguration().ReadFrom.AppSettings().CreateLogger())
                {
                    log.Error("The ValidateApiModel attribute caught a model validation error for user {0} with the following HTTP request: {1}",
                        actionContext.RequestContext.Principal.Identity.Name,
                        actionContext.Request);
                }

                // Send a 400 Bad Request response along with the model state.
                actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
            }
        }
開發者ID:txsll,項目名稱:SLLInvoices,代碼行數:16,代碼來源:ValidateApiModelAttribute.cs

示例8: EditFile

 public ActionResult EditFile(string editedText)
 {
     try
     {
         using (StreamWriter writer = new StreamWriter(Path.Combine(directory, "AboutPageText.txt")))
         {
             writer.Write(editedText);
         }
     }
     catch (System.Exception ex)
     {
         var logger = new LoggerConfiguration().WriteTo.File(@"C:\Users\Nour\Downloads\myapplog.txt", Serilog.Events.LogEventLevel.Error).CreateLogger();
         logger.Error(ex.Message, "cannot write file");
     }
     return View("Index");
 }
開發者ID:n-alomary,項目名稱:GameTrader,代碼行數:16,代碼來源:AdminController.cs

示例9: About

 public ActionResult About()
 {
     try
     {
         using (StreamReader reader = new StreamReader(@"C:\Users\Nour\Downloads\AboutPageText.txt"))
         {
             ViewBag.Message = reader.ReadToEnd();
         }
     }
     catch (Exception ex)
     {
         var logger = new LoggerConfiguration().WriteTo.File(@"C:\Users\Nour\Downloads\myapplog.txt", Serilog.Events.LogEventLevel.Error).CreateLogger();
         logger.Error(ex.Message, "This is possibly because file cannot be found.");
         ViewBag.Message = null;
     }
     return View();
 }
開發者ID:n-alomary,項目名稱:GameTrader,代碼行數:17,代碼來源:HomeController.cs

示例10: Main

        static void Main(string[] args)
        {

            //Configuration by AppSettings
            var logger = new LoggerConfiguration()
                .ReadFrom.AppSettings()
                .MinimumLevel.Debug()
                .Enrich.WithThreadId()
                .Enrich.WithProperty("MyMetaProperty", "Oh! the beautiful value!")
                .WriteTo.ColoredConsole()
                .CreateLogger();

            ////Configuration by code
            //var logger = new LoggerConfiguration()
            //    .MinimumLevel.Debug()
            //    .Enrich.WithThreadId()
            //    .Enrich.WithProperty("MyMetaProperty", "Oh! the beautiful value!")
            //    .WriteTo.ColoredConsole()
            //    .WriteTo.BrowserConsole(port: 9999, buffer: 50)
            //    .CreateLogger();

            OpenBrowserToBrowserLogUrl();

            logger.Information("Hello!");
            Thread.Sleep(1000);
            for (int i = 0; i < 100000; i++)
            {
                logger.Information("Hello this is a log from a server-side process!");
                Thread.Sleep(100);
                logger.Warning("Hello this is a warning from a server-side process!");
                logger.Debug("... and here is another log again ({IndexLoop})", i);
                Thread.Sleep(200);
                try
                {
                    ThrowExceptionWithStackTrace(4);
                }
                catch (Exception ex)
                {
                    logger.Error(ex, "An error has occured, really?");
                }

                Thread.Sleep(1000);
            }
        }
開發者ID:pmiossec,項目名稱:BrowserLog,代碼行數:44,代碼來源:Program.cs

示例11: Handle

        public override void Handle(ExceptionHandlerContext context)
        {
            using (var log = new LoggerConfiguration().ReadFrom.AppSettings().CreateLogger())
            {
                log.Error(context.Exception, "CustomApiExceptionHandler: An API exception occurred and a 500 Internal Server Error was returned");
                log.Information("CustomApiExceptionHandler: The request that caused the exception above was {0}", context.Request);
            }

            string message;

            if (context.Exception is Domain.Services.BusinessLogicException)
            {
                message = "The database update you requested cannot be made because it violates business logic rules — " + context.Exception.Message;
            }
            else if (context.Exception is System.Data.Entity.Infrastructure.DbUpdateException)
            {
                message = "An error occurred while trying to update the database.";

                if (context.Exception.InnerException != null)
                {
                    message += " " + context.Exception.InnerException.Message.Replace(" See the inner exception for details.", string.Empty);
                    if (context.Exception.InnerException.InnerException != null)
                        message += " " + context.Exception.InnerException.InnerException.Message + ".";
                }

                context.Result = new InternalServerErrorWithCustomMessageResult(message);
            }
            else
            {
                message = context.Exception.Message;
            }

            // Return a 500 Server Error with a message.
            context.Result = new InternalServerErrorWithCustomMessageResult(message);

            base.Handle(context);
        }
開發者ID:txsll,項目名稱:SLLInvoices,代碼行數:37,代碼來源:CustomApiExceptionHandler.cs

示例12: OnException

        // This creates a CustomHandleError attribute to be used in MVC controllers.
        // It is modeled after the code at https://stackoverflow.com/questions/23779991/can-web-config-httperrors-section-and-a-webapi-area-coexist.
        // If we are handling an exception and it is of type HttpException, keep the current URL and show the Error.cshtml view.
        // Create a TempDataDictionary and send it to the Error view for processing.
        // This is intended to catch all 500 errors.
        // Without it, some parts of MVC would let IIS handle the error, which bypasses the custom error page.
        public override void OnException(ExceptionContext filterContext)
        {
            if (filterContext.Exception != null && (filterContext.Exception is HttpException || filterContext.Exception is Domain.Services.BusinessLogicException))
            {
                string modelErrors = "<br>";

                foreach (ModelState modelState in filterContext.Controller.ViewData.ModelState.Values)
                    foreach (ModelError error in modelState.Errors)
                        modelErrors += error.ErrorMessage + "<br>";
                if (modelErrors.Length >= 4)
                    modelErrors = modelErrors.Substring(0, modelErrors.Length - 4);

                // Log the exception.
                using (var log = new LoggerConfiguration().ReadFrom.AppSettings().CreateLogger())
                {
                    string msg = "CustomHandleError: ";

                    if (filterContext.Exception is HttpException)
                        msg += "an HttpException occurred";
                    else if (filterContext.Exception is Domain.Services.BusinessLogicException)
                        msg += "a BusinessLogicException occurred";

                    log.Error(filterContext.Exception, msg);

                    if (!string.IsNullOrWhiteSpace(modelErrors))
                        log.Error("There were model errors: {0}", modelErrors.Replace("<br>", "; "));
                }

                TempDataDictionary tempData = new TempDataDictionary();
                tempData["ErrorMessage"] = filterContext.Exception.Message;

                if (!string.IsNullOrWhiteSpace(modelErrors))
                    tempData["ErrorMessage"] += modelErrors;

                int httpCode = (int) HttpStatusCode.InternalServerError;
                if (filterContext.Exception is HttpException)
                {
                    HttpException myException = ((HttpException) filterContext.Exception);
                    httpCode = myException.GetHttpCode();
                    tempData["HttpCode"] = httpCode;
                }
                if (filterContext.Exception is Domain.Services.BusinessLogicException)
                {
                    tempData["HttpCode"] = (int) HttpStatusCode.Forbidden;
                    httpCode = (int) HttpStatusCode.Forbidden;
                }

                filterContext.Result = new ViewResult { ViewName = "Error", TempData = tempData };
                filterContext.HttpContext.Response.StatusCode = httpCode;
                filterContext.HttpContext.Response.StatusDescription = filterContext.Exception.Message;
                filterContext.ExceptionHandled = true;
                filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
            }
            else
            {
                // Log the exception.
                using (var log = new LoggerConfiguration().ReadFrom.AppSettings().CreateLogger())
                {
                    log.Error(filterContext.Exception, "CustomHandleError: an unhandled exception occurred");
                }

                base.OnException(filterContext);
            }
        }
開發者ID:txsll,項目名稱:SLLInvoices,代碼行數:70,代碼來源:CustomHandleError.cs


注:本文中的Serilog.LoggerConfiguration.Error方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。