public override void Run() { var cs = CloudConfigurationManager.GetSetting("StorageConnectionString"); CloudStorageAccount storageAccount; CloudStorageAccount.TryParse(cs, out storageAccount); var log = new LoggerConfiguration().WriteTo.AzureTableStorage(storageAccount).CreateLogger(); log.Information("Who let azure out"); log.Information("Starting processing of messages"); // Initiates the message pump and callback is invoked for each message that is received, calling close on the client will stop the pump. _client.OnMessage((receivedMessage) => { try { // Process the message Trace.WriteLine("Processing Service Bus message: " + receivedMessage.SequenceNumber.ToString()); } catch(Exception e) { // Handle any message processing specific exceptions here } }); _completedEvent.WaitOne(); }
void Application_Start(object sender, EventArgs e) { // Code that runs on application startup AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); RouteConfig.RegisterRoutes(RouteTable.Routes); // Apply the HandleException attribute to all MVC controllers. // It extends the MVC HandleError attribute so that it catches HTTP errors with status 500 and displays them nicely // instead of defaulting to the IIS error page. GlobalFilters.Filters.Add(new CustomHandleError()); // Apply the CustomAuthorize filter to all MVC controllers. // It extends the MVC Authorize attribute to take care of role-checking and making sure user accounts have not been disabled. // To prevent a controller from needing authentication and authorization (like AccountController), use [AllowAnonymous]. // To enforce a role on an MVC controller or action, use [CustomAuthorize(Roles = "admin")]. GlobalFilters.Filters.Add(new CustomAuthorize()); // Apply the CustomApiAuthorize filter to all API controllers. // It extends the API Authorize attribute to take care of role-checking and making sure user accounts have not been disabled. // To enforce a role on an API controller or action, use [CustomApiAuthorize(Roles = "admin")]. GlobalConfiguration.Configuration.Filters.Add(new CustomApiAuthorize()); // Apply the ValidateApiModel attribute to all API controllers. // It extends the ActionFilterAttribute to perform model validation on DTOs that use the System.DataComponents.DataAnnotations annotations. // If the model does not validate, it returns a 400 Bad Request with error messages specified in the annotations. GlobalConfiguration.Configuration.Filters.Add(new ValidateApiModelAttribute()); // Serilog. using (var log = new LoggerConfiguration().ReadFrom.AppSettings().CreateLogger()) { log.Information("Application_Start: the SLLInvoices application has started"); } }
// // This method is invoked when the application has loaded and is ready to run. In this // method you should instantiate the window, load the UI into it and then make the window // visible. // // You have 17 seconds to return from this method, or iOS will terminate your application. // public override bool FinishedLaunching(UIApplication app, NSDictionary options) { Current = this; var log = new LoggerConfiguration().CreateLogger(); log.Information("Loading"); UIApplication.SharedApplication.StatusBarStyle = UIStatusBarStyle.LightContent; // create a new window instance based on the screen size window = new UIWindow(UIScreen.MainScreen.Bounds); // If you have defined a view, add it here: // window.RootViewController = navigationController; var rootNavigationController = Utilities.BuildNavigationController(); rootNavigationController.PushViewController(new ViewControllers.Login(), false); window.RootViewController = rootNavigationController; // make the window visible window.MakeKeyAndVisible(); Utilities.SetTintColor(); autoSuspendHelper.FinishedLaunching(app, options); return true; }
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"); }
void Application_End(object sender, EventArgs e) { // Serilog. using (var log = new LoggerConfiguration().ReadFrom.AppSettings().CreateLogger()) { log.Information("Application_End: the SLLInvoices application is being shut down"); } }
public static void ParameterizedLog() { // Create Logger var logger = new LoggerConfiguration() .WriteTo.Console() .CreateLogger(); // write structured data logger.Information("Processed {Number} records in {Time} ms", 500, 120); }
public static void HelloLog() { // Create Logger var logger = new LoggerConfiguration() .WriteTo.Console() .CreateLogger(); // Output logs logger.Information("Hello, Serilog!"); }
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); } }
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); }
public void Message( LoggerHistorySink sut, string message ) { var logger = new LoggerConfiguration().WriteTo.Sink( sut ).CreateLogger(); logger.Information( message ); var item = sut.Events.Only(); Assert.NotNull( item ); Assert.Equal( LogEventLevel.Information, item.Level ); }
public static void TemplateLog() { // Create Logger var logger = new LoggerConfiguration() .WriteTo.Console() .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); }
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 static void Main(string[] args) { var log = new LoggerConfiguration() .WriteTo.Console() .MinimumLevel.Debug() .CreateLogger(); var options = new Options(); if (CommandLine.Parser.Default.ParseArguments(args, options) == false) { log.Fatal("Problem parsing options!"); Environment.Exit(-1); } log.Information("Processing migrations"); var connectionStringVal = Config.ConnectionStrings[options.ConnectionStringName]; if (connectionStringVal == null) { log.Fatal("ERROR: Unable to get connection string from configuration"); Environment.Exit(-2); } var connectionString = connectionStringVal.ConnectionString; log.Debug("Connection string is {connectionString}", connectionString); var runner = new FluentRunner(connectionString, typeof(DipsContext).Assembly); try { runner.MigrateToLatest(); } catch (Exception e) { log.Fatal(e, "ERROR: problem while running migrations!"); Environment.Exit(-3); } log.Information("Migrations run successfully"); }
public DipsService() { var log = new LoggerConfiguration().Destructure.UsingAttributes().ReadAppSettings().CreateLogger(); Log.Logger = log; InitializeComponent(); var configuration = SetConfiguration(); ValidateCodeline = new ValidateCodelineProcessingService(configuration, log); ValidateTransaction = new ValidateTransctionRequestProcessingService(configuration, log); CheckThirdParty = new CheckThirdPartyProcessingService(configuration, log); CorrectCodeline = new CorrectCodelineProcessingService(configuration, log); CorrectTransaction = new CorrectTransactionProcessingService(configuration, log); GenerateVoucher = new GenerateCorrespondingVoucherProcessingService(configuration, log); GetVoucher = new GetVouchersInformationProcessingService(configuration, log); log.Information("Dips Service Initialised"); }
public void KafkaConnectionTest() { var log = new LoggerConfiguration() .WriteTo .Kafka(new KafkaSinkOptions(topic: "test", brokers: new[] { new Uri("http://*****:*****@now}", new { DateTimeOffset.Now.Hour, DateTimeOffset.Now.Minute }); log.CloseAndFlush(); Assert.IsTrue(true); }
public void PublicInterfaceReverseProxyTest() { Type iLogEventEnricherType = typeof(Serilog.Core.ILogEventEnricher); var resetEvent = new ManualResetEventSlim(); var instance = new PublicLogEventEnricherImpl(resetEvent); var proxy = instance.DuckCast(iLogEventEnricherType); var log = new Serilog.LoggerConfiguration() .Enrich.With((Serilog.Core.ILogEventEnricher)proxy) .MinimumLevel.Debug() .WriteTo.Console() .CreateLogger(); log.Information("Hello world"); Assert.True(resetEvent.Wait(5_000)); }
private static void Main() { var logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.ColoredConsole( outputTemplate: "{Timestamp:HH:mm:ss} ({ThreadId}) [{Level}] {Message:l}{NewLine:l}{Exception:l}") .WriteTo.Trace() .Enrich.WithProperty("App", "Test Harness") .Enrich.With(new ThreadIdEnricher(), new MachineNameEnricher()) .CreateLogger(); logger.Information("Just biting {Fruit} number {Count}", "Apple", 12); logger.ForContext<Program>().Information("Just biting {Fruit} number {Count:0000}", "Apple", 12); using (logger.BeginTimedOperation("Time a thread sleep for 2 seconds.")) { Thread.Sleep(1000); using (logger.BeginTimedOperation("And inside we try a Task.Delay for 2 seconds.")) { Task.Delay(2000).Wait(); } Thread.Sleep(1000); } using (logger.BeginTimedOperation("Using a passed in identifier", "test-loop")) { var a = ""; for (int i = 0; i < 1000; i++) { a += "b"; } } // Exceed a limit using (logger.BeginTimedOperation("This should execute within 1 second.",null, LogEventLevel.Debug, TimeSpan.FromSeconds(1))) { Thread.Sleep(1100); } Console.ReadKey(true); }
static void Main(string[] args) { var log = new LoggerConfiguration() .WriteTo.ColoredConsole() .CreateLogger(); try { // https://github.com/serilog/serilog/wiki/Getting-Started //log.Information("Starting log..."); var array = new int[] { 3, 1, 2, 4, 3 }; var result = TimeComplexity.solutionTapeEquilibrium(array); log.Information($"Result:{result}."); Console.ReadLine(); } catch (Exception exception) { log.Fatal(exception, "Fatal error"); } }
private static void Main(string[] args) { var logger = new LoggerConfiguration() .ReadFrom.AppSettings() .CreateLogger(); Log.Logger = logger; var system = ActorSystem.Create("loadtest"); // TODO: get worker and url:s from args var producer = Props.Create<RequestProducer>(()=> new RequestProducer(20, new [] { "http://localhost/", })); logger.Information("Starting up AkkaPump, press enter to stop pumping request"); var actorRef = system.ActorOf(producer, "requestProducer"); Console.ReadLine(); // TODO: find a better way to shutdown properly var result = actorRef.GracefulStop(TimeSpan.FromSeconds(60)).Result; Console.ReadLine(); }
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); }
public static void Run() { var logger = new Serilog.LoggerConfiguration() .WriteTo.File("seri.txt").CreateLogger(); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); var sw = Stopwatch.StartNew(); for (int i = 0; i < 100000; i++) { logger.Information(Guid.NewGuid().ToString()); } Console.WriteLine("come here:" + sw.Elapsed.TotalMilliseconds); Console.WriteLine("after wait:" + sw.Elapsed.TotalMilliseconds); sw.Stop(); Console.WriteLine("time: " + sw.Elapsed.TotalMilliseconds + "ms"); // line / elapsed Console.WriteLine(((double)100000 / sw.Elapsed.TotalMilliseconds) + "ms"); }
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); } }
// Handle unauthorized requests. // Set the status code to 403 and suppress re-directing to the login page, which is the default action. protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { if (!filterContext.HttpContext.User.Identity.IsAuthenticated) { // The user is not authenticated. base.HandleUnauthorizedRequest(filterContext); } else if (!this.Roles.Split(',').Any(filterContext.HttpContext.User.IsInRole)) { // Don't re-direct to the login page, which is the default behavior. filterContext.HttpContext.Response.SuppressFormsAuthenticationRedirect = true; // Return a 403 Forbidden result. This brings up the /403.html page with the correct 403 HTTP status. filterContext.HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.Forbidden; filterContext.HttpContext.Response.StatusDescription = "You are not authorized to view this page."; // Log the attempt to access an admin-only page. using (var log = new LoggerConfiguration().ReadFrom.AppSettings().CreateLogger()) { log.Information("User {0} was given a 403 Forbidden message when trying to access {1}", filterContext.HttpContext.User.Identity.Name, filterContext.HttpContext.Request.Path); } } else { base.HandleUnauthorizedRequest(filterContext); } }
protected override bool AuthorizeCore(HttpContextBase httpContext) { bool disableAuthentication = false; GenericIdentity identity; GenericPrincipal principal; string[] roles; #if DEBUG disableAuthentication = true; #endif if (disableAuthentication) { // Create a fake user and use this in debugging to disable authentication. identity = new GenericIdentity("alongoria"); roles = new string[] { "admin" }; principal = new GenericPrincipal(identity, roles); httpContext.User = principal; } else { HttpCookie authCookie = httpContext.Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); string username = authTicket.Name; // According to many articles and Ninject docs like: // https://github.com/ninject/Ninject.Web.Mvc/wiki/Filters-and-Scoped, // https://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=98, // https://stackoverflow.com/questions/29915192/unity-property-injection-on-authorizeattribute // MVC caches filters, which means dependency injection with .InRequestScope() does not work. // If we try to inject the _authorizationFilter with Ninject, there is a runtime error saying the DbContext has been disposed // on the second and all subsequent requests (works fine on the first request). using (_userService = new UserService()) { User user = _userService.GetByUsername(username); if (user == null) { // The user has a cookie, so they are in the Active Directory. // But they aren't in our local database (new employee, probably), so add them. User newUser = new User() { Username = username, IsActive = true, IsAdmin = false }; HttpCookie initialsCookie = httpContext.Request.Cookies[Configuration.GetAppSetting("UserInitialsCookieName")]; if (initialsCookie != null && !string.IsNullOrWhiteSpace(initialsCookie.Value)) { newUser.Initials = initialsCookie.Value; } else { if (username.Length > 1) newUser.Initials = username.Substring(0, 2); else newUser.Initials = "xx"; } _userService.Insert(newUser); user = _userService.GetByUsername(username); using (var log = new LoggerConfiguration().ReadFrom.AppSettings().CreateLogger()) { log.Information("A new user was added to the application: {0}", username); } } // End inserting new User and pulling it from the db. else { // If there's a cookie with initials, check its value to make sure our db value isn't out of date. HttpCookie initialsCookie = httpContext.Request.Cookies[Configuration.GetAppSetting("UserInitialsCookieName")]; if (initialsCookie != null && !string.IsNullOrWhiteSpace(initialsCookie.Value)) { if (!initialsCookie.Value.Equals(user.Initials, System.StringComparison.CurrentCultureIgnoreCase)) { user.Initials = initialsCookie.Value; _userService.Update(user); } } } if (!user.IsActive) { using (var log = new LoggerConfiguration().ReadFrom.AppSettings().CreateLogger()) { log.Warning("A user whose account was disabled attempted to log on to the application: {0}", username); } throw new HttpException(500, string.Format("The {0} account has been disabled.", authTicket.Name)); } if (user.IsAdmin) roles = new string[] { "admin" }; else roles = null; } identity = new GenericIdentity(username, "Forms"); principal = new GenericPrincipal(identity, roles); httpContext.User = principal; } } // Now that we have set httpContext.User appropriately, do the authorization check which will make sure user is in the proper Role. return base.AuthorizeCore(httpContext); }
private static void Main() { var logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.ColoredConsole( outputTemplate: "{Timestamp:HH:mm:ss} ({ThreadId}) [{Level}] {Message}{NewLine}{Exception}") .WriteTo.Trace() .Enrich.WithProperty("App", "Test Harness") .Enrich.With(new ThreadIdEnricher(), new MachineNameEnricher()) .CreateLogger(); logger.Information("Just biting {Fruit} number {Count}", "Apple", 12); logger.ForContext<Program>().Information("Just biting {Fruit} number {Count:0000}", "Apple", 12); using (logger.BeginTimedOperation("Time a thread sleep for 2 seconds.")) { Thread.Sleep(1000); using (logger.BeginTimedOperation("And inside we try a Task.Delay for 2 seconds.")) { Task.Delay(2000).Wait(); } Thread.Sleep(1000); } using (logger.BeginTimedOperation("Using a passed in identifier", "test-loop")) { var a = ""; for (int i = 0; i < 1000; i++) { a += "b"; } } // Exceed a limit using (logger.BeginTimedOperation("This should execute within 1 second.", null, LogEventLevel.Debug, TimeSpan.FromSeconds(1))) { Thread.Sleep(1100); } // Gauge var queue = new Queue<int>(); var gauge = logger.GaugeOperation("queue", "item(s)", () => queue.Count()); gauge.Write(); queue.Enqueue(20); gauge.Write(); queue.Dequeue(); gauge.Write(); // Counter var counter = logger.CountOperation("counter", "operation(s)", true, LogEventLevel.Debug); counter.Increment(); counter.Increment(); counter.Increment(); counter.Decrement(); Console.WriteLine("Press a key to exit."); Console.ReadKey(true); }
private void CreateEntryEnrichedWithUserInfo(object sender, RoutedEventArgs e) { var log = new LoggerConfiguration() .Enrich.FromLogContext() .WriteTo.Seq("http://localhost:5341") .CreateLogger(); using (LogContext.PushProperty("User", "GDP1")) using (LogContext.PushProperty("Lab", "EUHAWE3")) { log.Information("Info logged with user info"); } }
private void AddMultiplePropertiesToContextUsingCustomPropertyAttacher(object sender, RoutedEventArgs e) { Dictionary<string, object> properties = new Dictionary<string, object>(); properties.Add("SampleId", "EUANNA-20150112-1254896215"); properties.Add("User", "GDP1"); properties.Add("Lab", "EUHAWE3"); var log = new LoggerConfiguration() .Enrich.FromLogContext() .WriteTo.Seq("http://localhost:5341") .CreateLogger(); using (new MultiplePropertyPusher(properties)) { log.Information("This log entry includes two attached properties using a custom multiproperty attacher"); } }
private void AddMultiplePropertiesToContext(object sender, RoutedEventArgs e) { var log = new LoggerConfiguration() .Enrich.FromLogContext() .WriteTo.Seq("http://localhost:5341") .CreateLogger(); using (LogContext.PushProperty("User", "GDP1")) using (LogContext.PushProperty("Lab", "EUHAWE3")) { log.Information("This log entry includes two attached properties"); } }
private void AddAStructuredObjectToContext(object sender, RoutedEventArgs e) { var log = new LoggerConfiguration() .Enrich.FromLogContext() .WriteTo.Seq("http://localhost:5341") .CreateLogger(); // Instantiate a Person var person = new Person() { FirstName = "Dimitris", LastName = "Paxinos" }; using (LogContext.PushProperty("PersonDetails", person, destructureObjects: true)) { log.Information("This log entry includes a structured object"); } }
public static void Run() { var logger = new Serilog.LoggerConfiguration() .WriteTo.File("seri.txt").CreateLogger(); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); var sw = Stopwatch.StartNew(); for (int i = 0; i < 100000; i++) { logger.Information(Guid.NewGuid().ToString()); } Console.WriteLine("come here:" + sw.Elapsed.TotalMilliseconds); Console.WriteLine("after wait:" + sw.Elapsed.TotalMilliseconds); sw.Stop(); Console.WriteLine("time: " + sw.Elapsed.TotalMilliseconds + "ms"); // line / elapsed Console.WriteLine(((double)100000 / sw.Elapsed.TotalMilliseconds) + "ms"); }