示例#1
0
 /// <inheritdoc />
 public void Connect(IConnectContext connectContext)
 {
     seriLogger
     .ForContext("isReconnect", connectContext.IsReconnect)
     .Information("Tapeti: trying to connect to {host}:{port}/{virtualHost}",
                  connectContext.ConnectionParams.HostName,
                  connectContext.ConnectionParams.Port,
                  connectContext.ConnectionParams.VirtualHost);
 }
示例#2
0
 /// <summary>
 ///     Write the supplied information to a Serilog.ILogger
 /// </summary>
 /// <param name="logInfo">LogInfo</param>
 /// <param name="messageTemplate">string</param>
 /// <param name="logParameters">params object[]</param>
 public override void Write(LogInfo logInfo, string messageTemplate, params object[] logParameters)
 {
     Serilog.ILogger seriLogger;
     if (logInfo.Source.SourceType != null)
     {
         seriLogger = Log.ForContext(logInfo.Source.SourceType);
     }
     else
     {
         seriLogger = Log.ForContext("SourceContext", logInfo.Source.Source);
     }
     seriLogger.Write(ConvertLevel(logInfo.LogLevel), messageTemplate, logParameters);
 }
示例#3
0
        public ProductsController(IProductsService iProductsService
                                  , Serilog.ILogger logger
                                  , IStringLocalizer <SharedResource> sharedLocalizer
                                  , IStringLocalizer <ProductsController> localizer
                                  , IStringLocalizerFactory stringLocalizerFactory
                                  )
        {
            _IProductsService = iProductsService;

            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }
            else
            {
                _logger = logger.ForContext <ProductsController>();
            }

            _sharedLocalizer = sharedLocalizer;
            _localizer       = localizer;

            var assemblyName    = typeof(ProductsController).GetTypeInfo().Assembly.GetName().Name;
            var stringLocalizer = stringLocalizerFactory.Create("SharedResource", assemblyName);

            _stringLocalizerFactory = stringLocalizer;
        }
示例#4
0
        private static void ConfigureCompositionRoot(
            string connectionString,
            IExecutionContextAccessor executionContextAccessor,
            ILogger logger,
            EmailsConfiguration emailsConfiguration)
        {
            var containerBuilder = new ContainerBuilder();

            containerBuilder.RegisterModule(new LoggingModule(logger.ForContext("Module", "Meetings")));

            var loggerFactory = new SerilogLoggerFactory(logger);

            containerBuilder.RegisterModule(new DataAccessModule(connectionString, loggerFactory));

            containerBuilder.RegisterModule(new ProcessingModule());
            containerBuilder.RegisterModule(new EventsBusModule());
            containerBuilder.RegisterModule(new MediatorModule());
            containerBuilder.RegisterModule(new AuthenticationModule());
            containerBuilder.RegisterModule(new OutboxModule());
            containerBuilder.RegisterModule(new EmailModule(emailsConfiguration));
            containerBuilder.RegisterModule(new QuartzModule());

            containerBuilder.RegisterInstance(executionContextAccessor);

            _container = containerBuilder.Build();

            MeetingsCompositionRoot.SetContainer(_container);
        }
示例#5
0
        protected override void Append(LoggingEvent loggingEvent)
        {
            var serilogLevel = ConvertLevel(loggingEvent.Level);
            var logger       = _logger.ForContext(Serilog.Core.Constants.SourceContextPropertyName, loggingEvent.LoggerName);

            logger.Write(serilogLevel, loggingEvent.ExceptionObject, loggingEvent.MessageObject?.ToString());
        }
        private bool ProcessWorkItemWithLogging(WorkItemData sourceWorkItemData, int current, int totalWorkItem)
        {
            var sourceWorkItem = TfsExtensions.ToWorkItem(sourceWorkItemData);

            workItemLog = contextLog.ForContext("SourceWorkItemId", sourceWorkItem.Id);

            using (LogContext.PushProperty("sourceWorkItemTypeName", sourceWorkItem.Type.Name))
                using (LogContext.PushProperty("currentWorkItem", current))
                    using (LogContext.PushProperty("totalWorkItems", totalWorkItem))
                        using (LogContext.PushProperty("sourceWorkItemId", sourceWorkItem.Id))
                            using (LogContext.PushProperty("sourceRevisionInt", sourceWorkItem.Revision))
                                using (LogContext.PushProperty("targetWorkItemId", null))
                                {
                                    ProcessWorkItem(sourceWorkItemData, _config.WorkItemCreateRetryLimit);
                                    if (_config.PauseAfterEachWorkItem)
                                    {
                                        Console.WriteLine("Do you want to continue? (y/n)");
                                        if (Console.ReadKey().Key != ConsoleKey.Y)
                                        {
                                            workItemLog.Warning("USER ABORTED");
                                            return(false);
                                        }
                                    }
                                }
            return(true);
        }
示例#7
0
 public static void Run(List <Command> commands)
 {
     while (true)
     {
         string commandLine = Console.ReadLine();
         if (commandLine == null)
         {
             return;
         }
         if (commandLine == "quit")
         {
             return;
         }
         var args = ParseCommandArgs(commandLine);
         var cmd  = commands.FirstOrDefault(x => x.Name == args.Name);
         if (cmd == null)
         {
             Console.WriteLine("Command not found");
             continue;
         }
         try {
             cmd.Handler(args);
         } catch (Exception e) {
             logger
             .ForContext("CommandLine", commandLine)
             .Error(e, "ExecuteCommand error");
         }
     }
 }
示例#8
0
        protected BasePageController(MainNavigationPageKeys mainNavPageKey,
                                     TraffkTenantModelDbContext db,
                                     CurrentContextServices current,
                                     ILogger logger,
                                     ICacher cacher = null)
        {
            Requires.NonNull(db, nameof(db));
            Requires.NonNull(current, nameof(current));
            Requires.NonNull(logger, nameof(logger));

            MainNavPageKey = mainNavPageKey;
            Rdb            = db;
            Current        = current;

            Logger = logger.ForContext(new ILogEventEnricher[]
            {
                new PropertyEnricher(typeof(Type).Name, this.GetType().Name),
            });

            var u = current.User;

            if (cacher != null)
            {
                Cacher = cacher.CreateScope(GetType(), TenantId);
            }
        }
示例#9
0
        public void Configuration(IAppBuilder app)
        {
            var httpConfiguration = new HttpConfiguration
            {
                DependencyResolver = new AutofacWebApiDependencyResolver(_lifetimeScope)
            };

            httpConfiguration.MapHttpAttributeRoutes();

            app.SetLoggerFactory(new OwinLoggerFactory(_logger));
            app.Use <LoggerMiddleware>(new LoggerMiddlewareOptions(t => _logger.ForContext(t)));
            app.Use <PluginAuthMiddleware>(new PluginAuthMiddlewareOptions(t => _logger.ForContext(t)));
            app.UseAutofacMiddleware(_lifetimeScope);
            app.UseAutofacWebApi(httpConfiguration);
            app.UseWebApi(httpConfiguration);
        }
示例#10
0
        IDocumentStore ConfigureRaven()
        {
            var store = new DocumentStore {
                Urls     = new[] { Configuration["RavenDb:Url"] },
                Database = Configuration["RavenDb:Database"]
            };

            if (Environment.IsDevelopment())
            {
                store.OnBeforeQuery += (_, args)
                                       => args.QueryCustomization
                                       .WaitForNonStaleResults()
                                       .AfterQueryExecuted(result =>
                {
                    Log.ForContext("SourceContext", "Raven").Debug("{index} took {duration}", result.IndexName, result.DurationInMs);
                });
            }

            try
            {
                store.Initialize();
                Log.Information("Connection to {url} document store established.", store.Urls[0]);
            }
            catch (Exception ex)
            {
                throw new ApplicationException(
                          $"Failed to establish connection to \"{store.Urls[0]}\" document store!" +
                          $"Please check if https is properly configured in order to use the certificate.", ex);
            }

            try
            {
                var record = store.Maintenance.Server.Send(new GetDatabaseRecordOperation(store.Database));
                if (record == null)
                {
                    store.Maintenance.Server
                    .Send(new CreateDatabaseOperation(new DatabaseRecord(store.Database)));

                    Log.Debug("{database} document store database created.", store.Database);
                }
            }
            catch (Exception ex)
            {
                throw new ApplicationException(
                          $"Failed to ensure that \"{store.Database}\" document store database exists!", ex);
            }

            try
            {
                IndexCreation.CreateIndexes(Assembly.GetExecutingAssembly(), store);
                Log.Information("{database} document store database indexes created or updated.", store.Database);
            }
            catch (Exception ex)
            {
                throw new ApplicationException($"Failed to create or update \"{store.Database}\" document store database indexes!", ex);
            }

            return(store);
        }
示例#11
0
        public static void Initialize(
            string connectionString,
            ILogger logger)
        {
            var moduleLogger = logger.ForContext("Module", "ParcelLockers");

            ConfigureCompositionRoot(connectionString, moduleLogger);
        }
示例#12
0
 public SerilogLoggerAdapter(SerilogLogger logger)
 {
     if (logger == null)
     {
         throw new ArgumentNullException(nameof(logger));
     }
     _logger = logger.ForContext(this);
 }
示例#13
0
 internal virtual void DumpInfo(bool list)
 {
     Log.ForContext("DumpInfo").Info("{Type} #{Id} {Name}", GetType().Name, ObjectId, Name);
     if (list)
     {
         VisitChilds <SceneObject>(a => a.DumpInfo(false));
     }
 }
示例#14
0
 public SerilogLogger(Serilog.ILogger logger)
 {
     if (logger == null)
     {
         throw new ArgumentNullException("logger");
     }
     _logger = logger.ForContext(typeof(T));
 }
示例#15
0
 public WorkflowManager(IComponentContext componentContext, IWorkflowDescriptionFinder finder, IBackgroundJobClient backgroundJobClient, ULODBEntities db, Serilog.ILogger log, ICacher cacher)
 {
     ComponentContext    = componentContext;
     Finder              = finder;
     BackgroundJobClient = backgroundJobClient;
     DB     = db;
     Log    = log.ForContext <WorkflowManager>();
     Cacher = cacher;
 }
示例#16
0
 public SerilogLogger(
     [NotNull] SerilogLoggerProvider provider,
     [NotNull] SLogger logger,
     string name)
 {
     _provider = provider;
     _name     = name;
     _logger   = logger.ForContext(Constants.SourceContextPropertyName, name);
 }
示例#17
0
 public ICompetingConsumer CreateReplicatingConsumer(string streamName, string groupName)
 {
     return(new ReplicatingConsumer(
                _destinationConnection.Value,
                _logger.ForContext <ReplicatingConsumer>(),
                _appSettings,
                streamName,
                groupName
                ));
 }
 public static Serilog.ILogger Here(this Serilog.ILogger logger,
                                    [CallerMemberName] string memberName    = "",
                                    [CallerFilePath] string sourceFilePath  = "",
                                    [CallerLineNumber] int sourceLineNumber = 0)
 {
     return(logger
            .ForContext("MemberName", memberName)
            .ForContext("FilePath", Path.GetFileName(sourceFilePath))
            .ForContext("LineNumber", sourceLineNumber));
 }
 internal void TraceWriteLine(LogEventLevel level, string message, Dictionary <string, object> properties = null)
 {
     if (properties != null)
     {
         foreach (var item in properties)
         {
             workItemLog = workItemLog.ForContext(item.Key, item.Value);
         }
     }
     workItemLog.Write(level, workItemLogTeamplate + message);
 }
示例#20
0
        /// <inheritdoc/>
        public void Log(LogEvent logEvent)
        {
            LogEventLevel serilogLogLevel = ConvertLogLevel(logEvent.LogLevel);
            var           logger          = _logger;

            if (!string.IsNullOrWhiteSpace(logEvent.EventId))
            {
                logger = _logger.ForContext("EventId", logEvent.EventId);
            }

            logger.Write(serilogLogLevel, logEvent.Exception, logEvent.Message, logEvent.PropertyValues);
        }
示例#21
0
 public ActionResult Create(Group group)
 {
     if (ModelState.IsValid)
     {
         _context.Groups.Add(group);
         _context.SaveChanges();
         return(RedirectToAction("Index"));
     }
     //var userDTO = _mapper.Map<UserDTO>(user);
     _logger.ForContext("User", _httpContextAccessor.HttpContext.User.Identity.Name).Information("Data Added Successfully");
     return(View(group));
 }
        public static void Initialize(
            string connectionString,
            IExecutionContextAccessor executionContextAccessor,
            ILogger logger)
        {
            var moduleLogger = logger.ForContext("Module", "Payments");

            ConfigureCompositionRoot(connectionString, executionContextAccessor, moduleLogger);

            QuartzStartup.Initialize(moduleLogger);

            EventsBusStartup.Initialize(moduleLogger);
        }
示例#23
0
        public CustomersController(ICustomerService iCustomerService, Serilog.ILogger logger)
        {
            _ICustomerService = iCustomerService;

            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }
            else
            {
                _logger = logger.ForContext <CustomersController>();
            }
        }
        public TokenController(Serilog.ILogger logger, IOptionsSnapshot <Settings> settings, ILoginService iLoginService)
        {
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }
            else
            {
                _logger = logger.ForContext <TokenController>();
            }

            _settings = settings;

            _ILoginService = iLoginService;
        }
示例#25
0
        public ProductsController(IProductsService iProductsService
                                  , Serilog.ILogger logger
                                  )
        {
            _IProductsService = iProductsService;

            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }
            else
            {
                _logger = logger.ForContext <ProductsController>();
            }
        }
示例#26
0
        static ILogger LogForErrorContext(HttpContext httpContext)
        {
            var request = httpContext.Request;

            var result = Log
                         .ForContext("RequestHeaders", request.Headers.ToDictionary(h => h.Key, h => h.Value.ToString()), destructureObjects: true)
                         .ForContext("RequestHost", request.Host)
                         .ForContext("RequestProtocol", request.Protocol);

            if (request.HasFormContentType)
            {
                result = result.ForContext("RequestForm", request.Form.ToDictionary(v => v.Key, v => v.Value.ToString()));
            }

            return(result);
        }
示例#27
0
        protected BaseJobRunner(
            TraffkGlobalDbContext globalContext,
            IJobInfoFinder jobInfoFinder,
            ILogger logger)
        {
            GlobalContext = globalContext;
            InstanceId    = Interlocked.Increment(ref InstanceId_s);
            JobInfo       = jobInfoFinder.JobInfo;

            Logger = logger.ForContext(new ILogEventEnricher[]
            {
                new PropertyEnricher(nameof(InstanceId), InstanceId),
                new PropertyEnricher(nameof(JobInfo.JobId), JobInfo?.JobId),
                new PropertyEnricher(typeof(Type).Name, GetType().Name),
            });

            Logger.Information(ConstructedText);
        }
        public static void Initialize(
            string connectionString,
            IExecutionContextAccessor executionContextAccessor,
            ILogger logger,
            EmailsConfiguration emailsConfiguration,
            IEventsBus eventsBus,
            bool runQuartz = true)
        {
            var moduleLogger = logger.ForContext("Module", "Payments");

            ConfigureCompositionRoot(connectionString, executionContextAccessor, moduleLogger, emailsConfiguration, eventsBus, runQuartz);

            if (runQuartz)
            {
                QuartzStartup.Initialize(moduleLogger);
            }

            EventsBusStartup.Initialize(moduleLogger);
        }
 public void LogInInfo(string username, string infotype, string requestUrl)
 {
     try
     {
         _logger.ForContext("Username", username)
         .ForContext("Infotype", infotype)
         .ForContext("RequestUrl", requestUrl)
         .Information("User {username} logged in", username);
     }
     catch (Exception ex)
     {
         LogException(ex, username, requestUrl);
     }
 }
示例#30
0
        /// <summary>
        /// Creates a new instance of the <see cref="AppRegistry"/>
        /// </summary>
        /// <param name="configuration">The application configuration to be registered with the container</param>
        /// <param name="logger">The application logger to be registered with the container</param>
        public AppRegistry(IConfiguration configuration, ILogger logger)
        {
            For <IConfiguration>().Use(configuration);

            // Binds the "Settings" section from appsettings.json to AppSettings
            var settings = Bind <AppSettings>(configuration, "Settings");

            ForSingletonOf <AppSettings>().Use(settings);

            // Automatically sets the Serilog source context to the requesting type
            For <ILogger>()
            .Use(ctx => logger.ForContext(ctx.ParentType ?? ctx.RootType))
            .AlwaysUnique();

            // Default
            ForSingletonOf <IEventStoreConnection>().Use(
                ctx => CreateEventStoreConnection(
                    ctx.GetInstance <Serilog.ILogger>(),
                    ctx.GetInstance <AppSettings>().SourceEventStoreConnectionString,
                    "Ditto:Source"
                    ));

            ForSingletonOf <IEventStoreConnection>().Add(
                ctx => CreateEventStoreConnection(
                    ctx.GetInstance <Serilog.ILogger>(),
                    ctx.GetInstance <AppSettings>().DestinationEventStoreConnectionString,
                    "Ditto:Destination"
                    ))
            .Named("Destination");

            For <ICheckpointManager>().Use <EventStoreCheckpointManager>(ctx =>
                                                                         new EventStoreCheckpointManager(ctx.GetInstance <IEventStoreConnection>("Destination"), ctx.GetInstance <AppSettings>(), ctx.GetInstance <ILogger>())
                                                                         );

            For <IConsumerManager>().Use <ConsumerManager>();

            // Register replicating consumers
            foreach (var streamName in settings.GetStreamsToReplicate())
            {
                For <IConsumer>().Add(CreateReplicatingConsumer(streamName));
            }
        }