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)"); } }
private static void Main() { var log = new LoggerConfiguration() .MinimumLevel.Verbose() .WriteTo.Console() .WriteTo.File("log.txt", rollingInterval: RollingInterval.Day, rollOnFileSizeLimit: true, fileSizeLimitBytes: 512) .CreateLogger(); log.Information("Hello, Serilog!"); var position = new { Latitude = 25, Longitude = 134 }; var elapsedMs = 34; var products = new List <string> { "Paper", "Pencil", "Pen" }; log.Information("Processed {Position} in {Elapsed} ms.", position, elapsedMs); log.Information("Ordered {@products}", products); log.Information("Added {UserName}", "Sarah"); log.Information("Added {UserName:l}", "Sarah"); log.Information("PI is {PI}", Math.PI); log.Information("PI is {PI:0.00}", Math.PI); log.Verbose("This is verbose."); log.Debug("This is debug."); log.Warning("This is warning"); log.Error("This is error"); log.Fatal("This is Fatal"); Log.CloseAndFlush(); Console.ReadKey(); }
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"); }
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); }
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); }
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"); }
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); }
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); } }
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"); }
public ActionResult EditFile() { try { using (StreamReader reader = new StreamReader(Path.Combine(directory, "AboutPageText.txt"))) { ViewData["FileTextToEdit"] = reader.ReadToEnd(); } } 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 read file"); } return View("EditFile",ViewBag); }
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(); }
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); } }
static void Main(string[] args) { //Create Logger var logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.ColoredConsole() .WriteTo.RollingFile(@"C:\Users\Daniel Contreras\source\repos\Serilog\Serilog\Log-{Date}.txt") .CreateLogger(); // prepare data var order = new { Id = 12, Total = 128.50, CustomerId = 72 }; var customer = new { Id = 72, Name = "John Smith" }; // write log message logger.Information("New orders {OrderId} by {Customer}", order.Id, customer); logger.Debug("Debugging message"); logger.Information("Information message"); logger.Warning("Warning message"); logger.Error("Error message"); logger.Fatal("Fatal message"); Console.ReadKey(); }
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); }
// 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); } }
static async Task Main(string[] args) { var logger = new Serilog.LoggerConfiguration() .MinimumLevel.Verbose() .WriteTo.Console(theme: AnsiConsoleTheme.Code) .CreateLogger(); const string host = "school.sibears.ru"; const int port = 4040; const string RIGHT = "right :)"; const string WRONG = "wrong :("; const string NOT_FAST = "you are not so fast :("; const string FLAG = "This is flag:"; try { using (var client = new WebClient(host, port, 8000)) { var watch = Stopwatch.StartNew(); while (client.Connected) { var data = await client.Reader.ReadLineAsync(); logger.Information($"Received: {data}"); if (data.Contains(WRONG, StringComparison.OrdinalIgnoreCase) || data.Contains(NOT_FAST, StringComparison.OrdinalIgnoreCase)) { client.Terminate(); break; } if (data.Contains(RIGHT, StringComparison.OrdinalIgnoreCase)) { client.Reader.DiscardBufferedData(); continue; } if (data.StartsWith(FLAG, StringComparison.InvariantCultureIgnoreCase)) { Console.Write($"\n{data.Substring(data.IndexOf(':') + 2).Trim()}\n\n"); break; } // Process data. var vector = data.Split(' ', StringSplitOptions.RemoveEmptyEntries); BigInteger a, b; try { a = BigInteger.Parse(vector[0]); b = BigInteger.Parse(vector[2]); } catch (Exception ex) { logger.Error(ex, ex.Message); } // Send back some data. var response = BigInteger.Multiply(a, b).ToString(); logger.Information($"Send: {response}"); await client.Writer.WriteLineAsync(response); await client.Writer.FlushAsync(); } watch.Stop(); logger.Information($"Time: {watch.Elapsed.TotalSeconds} ms"); } } catch (SocketException se) { logger.Error(se.Message); } }