Пример #1
0
        public int LogChangedValue(AspectContext context)
        {
            var entity = (BaseEntity)context.Method.Args[0];
            Dictionary<string, EntityColumn> changedColumns = entity.GetChangedColumns();
            if (changedColumns.Count == 0)
                return 0;

            var logContext = new LogContext {EntityName = entity.EntityName, TableName = entity.TableName};

            foreach (var c in changedColumns)
            {
                logContext.Values.Add(c.Key, new ChangedEntityColumn(c.Value.OldValue, c.Value.CurrentValue));
            }

            try
            {
                LogManager.Instance.Write(logContext, true);
            }
            catch (Exception exp)
            {
                throw exp;
            }

            return changedColumns.Count;
        }
Пример #2
0
        public LogEntry Log(string message, LogLevel logLevel = LogLevel.Verbose, string category = null)
        {
            if (string.IsNullOrWhiteSpace(message))
            {
                throw new ArgumentNullException("message");
            }

            var logRecord = new LogRecord
            {
                ID = Guid.NewGuid(),
                Timestamp = DateTime.UtcNow,
                Message = message,
                LogLevelName = logLevel.ToString(),
                LogLevelValue = (int)logLevel,
                Category = category,
            };

            if (logLevel != LogLevel.None && logLevel >= LogLevel)
            {
                using (var db = new LogContext())
                {
                    db.LogRecords.Add(logRecord);
                    db.SaveChangesSync();
                }
            }

            return logRecord;
        }
Пример #3
0
 public void TestSetContextWithNullLogContextProperties()
 {
     var logContext = new LogContext(null);
     var logger = new Logger();
     logger.SetContext(logContext);
     Assert.Equal(0, logger.Properties.Count);
 }
		protected virtual void LogUnauthorized(HttpActionContext actionContext, HmacResult result, Customer customer)
		{
			try
			{
				var logger = EngineContext.Current.Resolve<ILogger>();
				var localization = EngineContext.Current.Resolve<ILocalizationService>();

				string strResult = result.ToString();
				string description = localization.GetResource("Admin.WebApi.AuthResult." + strResult, 0, false, strResult);

				var logContext = new LogContext()
				{
					ShortMessage = localization.GetResource("Admin.WebApi.UnauthorizedRequest").FormatWith(strResult),
					FullMessage = "{0}\r\n{1}".FormatWith(description, actionContext.Request.Headers.ToString()),
					LogLevel = LogLevel.Warning,
					Customer = customer,
					HashNotFullMessage = true,
					HashIpAddress = true
				};

				logger.InsertLog(logContext);
			}
			catch (Exception exc)
			{
				exc.Dump();
			}
		}
Пример #5
0
        public void TreeCreated(DbCommandTreeInterceptionContext interceptionContext)
        {
            var dbCommandTreeKind = interceptionContext.Result.CommandTreeKind;
            var context = interceptionContext.DbContexts.First();
            var auditContenxt = new LogContext();

            switch (dbCommandTreeKind)
            {
                case DbCommandTreeKind.Insert:
                    var addedEntries = context.ChangeTracker.Entries()
                        .Where(e => e.State == EntityState.Added && e.IsAttr<AuditableAttribute>())
                        .ToList();

                    foreach (var entry in addedEntries)
                    {
                        auditContenxt.ApplyAuditLog(context, entry);
                    }
                    break;
                case DbCommandTreeKind.Update:
                case DbCommandTreeKind.Delete:
                    var entries = context.ChangeTracker.Entries().Where(
                        e => (e.State == EntityState.Deleted || e.State == EntityState.Modified)
                             && e.IsAttr<AuditableAttribute>()).ToList();

                    foreach (var entry in entries)
                    {
                        auditContenxt.ApplyAuditLog(context, entry);
                    }
                    break;
            }
        }
Пример #6
0
 static void PushLog(object sender, LogContext e)
 {
   foreach (var appender in APPENDERS)
   {
     appender.Push(e);
   }
 }
Пример #7
0
        public Result(LogContext logContext)
        {
            Id = Guid.NewGuid();
            Json = new JObject();
            Json.Add(JSonKeys.LogType, logContext.LogType);
            Json.Add(JSonKeys.MachineName, System.Environment.MachineName);

            Canceled = false;
            MetaData = new Dictionary<string, string>();
        }
Пример #8
0
        /// <summary>
        /// Provider interface function for logging health event
        /// </summary>
        /// <param name="logContext"></param>
        /// <param name="eventId"></param>
        /// <param name="exception"></param>
        /// <param name="additionalInfo"></param>
        /// 
        internal override void LogEngineHealthEvent(LogContext logContext, int eventId, Exception exception, Dictionary<String, String> additionalInfo)
        {
            StringBuilder payload = new StringBuilder();

            AppendException(payload, exception);
            payload.AppendLine();
            AppendAdditionalInfo(payload, additionalInfo);

            WriteEvent(PSEventId.Engine_Health, PSChannel.Operational, PSOpcode.Exception, PSTask.ExecutePipeline, logContext, payload.ToString());
        }
Пример #9
0
        public void TestSetContextDoesNotSetNonPropertyKeysProperty()
        {
            var logContext = new LogContext();
            var logger = new Logger();

            logContext.Properties["k1"] = "v1";
            logger.SetContext(logContext);

            Assert.Equal(0, logger.Properties.Count);
            Assert.Equal(null, logger.GetProperty("k1"));
        }
Пример #10
0
        public static void Main()
        {
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<LogContext, Configuration>());

            using (var db = new LogContext())
            {
                Log test = new Log() { LogDate = DateTime.Now, LogQuery = "alabala" };
                db.Logs.Add(test);
                db.SaveChanges();
            }
        }
Пример #11
0
        public static void Writer(string query)
        {
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<LogContext, Configuration>());

            using (var db = new LogContext())
            {
                Log newLog = new Log() { LogDate = DateTime.Now, LogQuery = query };
                db.Logs.Add(newLog);
                db.SaveChanges();
            }
        }
Пример #12
0
        public List<ILogEntry> GetLog(DateTime fromDate, DateTime toDate)
        {
            using (var lb = new LogContext())
            {
                var query = (from l in lb.Logs
                            where l.Date <= toDate && l.Date >= fromDate
                             select l).ToList<ILogEntry>();

                return query;
            }
        }
Пример #13
0
        public Logger(string name, ILoggingTarget target, bool isInfo = false, bool isDebug = false, bool traceAdditionalInfo = false)
        {
            this.Name = name;
            this.loggingTarget = target;

            this.isInfo = isInfo;
            this.isDebug = isDebug;
            this.traceAdditionalInfo = traceAdditionalInfo;

            this.loggingTarget.Init(this);
            Context = null;
        }
Пример #14
0
 //template method
 public void Write(LogContext context)
 {
     try
     {
         WriteInternal(context);
     }
     catch
     {
         if (NextLogger != null)
             NextLogger.Write(context);
     }
 }
Пример #15
0
 public void OnNext(IEnumerable<StatisticEvent> value)
 {
     using(var context = new LogContext())
     {
         foreach (var statisticEvent in value)
         {
             
             context.Set<StatisticEvent>().Add(statisticEvent);
         }
         context.SaveChanges();
     }
 }
Пример #16
0
        public void ReaderExecuted(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
        {
            // just for update and delete commands
            if (command.CommandText.StartsWith("insert", StringComparison.InvariantCultureIgnoreCase))
            {
                var context = interceptionContext.DbContexts.First();
                var entries = context.ChangeTracker.Entries().Where(e => e.State == EntityState.Added).ToList();

                var auditContenxt = new LogContext();
                foreach (var entry in entries)
                {
                    auditContenxt.ApplyAuditLog(context, entry);
                }
            }
        }
Пример #17
0
        protected override void WriteInternal(LogContext context)
        {
            using (TextWriter tw = File.AppendText("logs.txt"))
            {
                //direkt context'i basarak
                tw.WriteLine(DateTime.Now.ToString() + "=>" + context);

                //kolonlar arasında dolaşarak
                //foreach (var c in context.Values)
                //{
                //    tw.WriteLine(DateTime.Now.ToString() + "=>" + c.ToString());
                //}

                tw.WriteLine("#logged!!!");
            }
        }
Пример #18
0
        public void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
        {
            // just for update and delete commands
            if (command.CommandText.StartsWith("update", StringComparison.InvariantCultureIgnoreCase) ||
                command.CommandText.StartsWith("delete", StringComparison.InvariantCultureIgnoreCase))
            {
                var context = interceptionContext.DbContexts.First();
                var entries = context.ChangeTracker.Entries().Where(
                    e => e.State == EntityState.Deleted || e.State == EntityState.Modified).ToList();

                var auditContenxt = new LogContext();
                foreach (var entry in entries)
                {
                    auditContenxt.ApplyAuditLog(context, entry);
                }
            }
        }
Пример #19
0
 protected override void WriteInternal(LogContext context)
 {
     //todo@onuar: 110812 userContext buraya taşınacak. yani login olan user'ın bilgileri
     //aklımda yarım yamalak şeyler var ama henüz oturamadım.
     List<BaseEntity> logEntities = new List<BaseEntity>();
     foreach (var c in context.Values)
     {
         BaseEntity logEntity = new BaseEntity() { EntityName = "Log" };
         EntityColumn ec = (EntityColumn)c.Value;
         logEntity.SetValue<string>("OldValue", ConvertionHelper.ConvertValue<string>(ec.OldValue));
         logEntity.SetValue<string>("NewValue", ConvertionHelper.ConvertValue<string>(ec.CurrentValue));
         logEntities.Add(logEntity);
     }
     //todo@onuar: 110812 transaction ile database'e yazdırılacak
     //entityManager ile olmuyor çünkü loggerPlugins projesi, hrc.library'i direkt referans almıyor.
     //referans gösteremiyoruz çünki circleDependency hatası yiyoruz. ya dbAccessLayer dışarı alınacak ya da başka bir şey
 }
Пример #20
0
 private static void FillEventArgs(Hashtable mapArgs, LogContext logContext)
 {
     mapArgs["Severity"] = logContext.Severity;
     mapArgs["SequenceNumber"] = logContext.SequenceNumber;
     mapArgs["HostName"] = logContext.HostName;
     mapArgs["HostVersion"] = logContext.HostVersion;
     mapArgs["HostId"] = logContext.HostId;
     mapArgs["EngineVersion"] = logContext.EngineVersion;
     mapArgs["RunspaceId"] = logContext.RunspaceId;
     mapArgs["PipelineId"] = logContext.PipelineId;
     mapArgs["CommandName"] = logContext.CommandName;
     mapArgs["CommandType"] = logContext.CommandType;
     mapArgs["ScriptName"] = logContext.ScriptName;
     mapArgs["CommandPath"] = logContext.CommandPath;
     mapArgs["CommandLine"] = logContext.CommandLine;
     mapArgs["User"] = logContext.User;
     mapArgs["Time"] = logContext.Time;
 }
Пример #21
0
        public void TestClearContextClearsOnlyPropertyKeysProperties()
        {
            var logContext = new LogContext();
            var logger = new Logger();

            foreach (var propertyKeyField in LogContext.PropertyKey.Fields)
            {
                var propertyKey = propertyKeyField.GetValue(logContext) as string;
                logContext.Properties[propertyKey] = propertyKey;
            }

            logger.SetContext(logContext);
            logger.SetProperty("k1", "v1");
            logger.ClearContext();

            Assert.Equal(1, logger.Properties.Count);
            Assert.Equal("v1", logger.GetProperty("k1"));
        }
Пример #22
0
        protected override void WriteInternal(LogContext context)
        {
            var logEntities = new List<BaseEntity>();
            foreach (var c in context.Values)
            {
                BaseEntity logEntity = new BaseEntity() { EntityName = "DataLog" };
                var ec = (ChangedEntityColumn)c.Value;
                logEntity.SetValue<DateTime>("ModifiedDate", DateTime.Now);
                logEntity.SetValue<string>("EntityName", context.EntityName);
                logEntity.SetValue<string>("TableName", context.TableName);
                logEntity.SetValue<string>("ColumnName", c.Key);
                logEntity.SetValue<string>("OldValue", ConvertionHelper.ConvertValue<string>(ec.OldValue));
                logEntity.SetValue<string>("NewValue", ConvertionHelper.ConvertValue<string>(ec.CurrentValue));
                logEntities.Add(logEntity);

                //todo@onuar: transaction
                EntityManager.Insert(logEntity);
            }
        }
Пример #23
0
        public void TestSetContextSetsOnlyPropertyKeys()
        {
            var logContext = new LogContext();
            var logger = new Logger();

            foreach (var propertyKeyField in LogContext.PropertyKey.Fields)
            {
                var propertyKey = propertyKeyField.GetValue(logContext) as string;
                logContext.Properties[propertyKey] = propertyKey;
            }

            logger.SetContext(logContext);
            Assert.Equal(logContext.Properties.Count, logger.Properties.Count);

            foreach (var propertyKeyField in LogContext.PropertyKey.Fields)
            {
                var propertyKey = propertyKeyField.GetValue(logContext) as string;
                var propertyValue = logger.GetProperty(propertyKey);

                Assert.Equal(logContext.Properties[propertyValue], propertyValue);
            }
        }
Пример #24
0
 public override void Before(MethodInfo methodUnderTest)
 {
     Disposables.TryAdd(methodUnderTest.Name, LogContext.PushProperty("Test", methodUnderTest.Name));
 }
Пример #25
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, LogContext context)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            LogContextInitializer.Initialize(context);

            app.UseMvc();
        }
        private void LogRequestAndResponse(IRestResponse response, Stopwatch stopwatch)
        {
            if (this.Configuration.LoggerConfiguration != null)
            {
                Log.Logger = this.Configuration.LoggerConfiguration.CreateLogger();
            }

            var uri = this.BuildUri(response.Request);

            string[] ignoredProperties = this.GetIgnoredProperties(response.Request);
            var      properties        = new Dictionary <string, object>();

            if (this.AdditionalProperties?.Any() == true)
            {
                foreach (var item in this.AdditionalProperties)
                {
                    properties.Add(item.Key, item.Value);
                }
            }

            properties.Add("Agent", "RestSharp");
            properties.Add("ElapsedMilliseconds", stopwatch.ElapsedMilliseconds);
            properties.Add("Method", response.Request.Method.ToString());
            properties.Add("Url", uri.AbsoluteUri);
            properties.Add("Host", uri.Host);
            properties.Add("Path", uri.AbsolutePath);
            properties.Add("Port", uri.Port);
            properties.Add("QueryString", uri.Query);
            properties.Add("Query", this.GetRequestQueryStringAsObject(response.Request));
            properties.Add("RequestBody", this.GetRequestBody(response.Request));
            properties.Add("RequestHeaders", this.GetRequestHeaders(response.Request));
            properties.Add("StatusCode", (int)response.StatusCode);
            properties.Add("StatusCodeFamily", ((int)response.StatusCode).ToString()[0] + "XX");
            properties.Add("StatusDescription", response.StatusDescription?.Replace(" ", ""));
            properties.Add("ResponseStatus", response.ResponseStatus.ToString());
            properties.Add("ProtocolVersion", response.ProtocolVersion);
            properties.Add("IsSuccessful", response.IsSuccessful);
            properties.Add("ErrorMessage", response.ErrorMessage);
            properties.Add("ErrorException", response.ErrorException);
            properties.Add("ResponseContent", this.GetResponseContent(response));
            properties.Add("ContentLength", response.ContentLength);
            properties.Add("ContentType", response.ContentType);
            properties.Add("ResponseHeaders", this.GetResponseHeaders(response));
            properties.Add("Environment", Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"));

            foreach (var property in properties)
            {
                if (ignoredProperties.Contains(property.Key) == false)
                {
                    LogContext.PushProperty(property.Key, property.Value);
                }
            }

            if (response.IsSuccessful)
            {
                Log.Information(this.Configuration.MessageTemplateForSuccess);
            }
            else
            {
                Log.Error(this.Configuration.MessageTemplateForSuccess);
            }
        }
Пример #27
0
 /// <summary>
 /// When exception occures, log it to event log.
 /// </summary>
 /// <param name="messageTitle">Title message</param>
 /// <param name="ex">Exception to log</param>
 private void LogExceptionToEventLog(string messageTitle, Exception ex)
 {
     AddError(messageTitle + ": " + ex.Message);
     LogContext.LogEventToCurrent(EventType.ERROR, "Content", "PUBLISHDOC", EventLogProvider.GetExceptionLogMessage(ex), RequestContext.RawURL, currentUser.UserID, currentUser.UserName, 0, null, RequestContext.UserHostAddress, currentSiteId, SystemContext.MachineName, RequestContext.URLReferrer, RequestContext.UserAgent, DateTime.Now);
 }
 public async Task Invoke(HttpContext context)
 {
     using (LogContext.PushProperty("Address", context.Connection.RemoteIpAddress)) {
         await _next.Invoke(context).ConfigureAwait(false);
     }
 }
Пример #29
0
            public async Task Send(SendEndpointContext clientContext)
            {
                LogContext.SetCurrentIfNull(_context.LogContext);

                var context = new AzureServiceBusSendContext <T>(_message, _cancellationToken);

                CopyIncomingIdentifiersIfPresent(context);

                await _pipe.Send(context).ConfigureAwait(false);

                var activity = LogContext.IfEnabled(OperationName.Transport.Send)?.StartSendActivity(context,
                                                                                                     (nameof(context.PartitionKey), context.PartitionKey),
                                                                                                     (nameof(context.SessionId), context.SessionId));

                try
                {
                    if (IsCancelScheduledSend(context, out var sequenceNumber))
                    {
                        await CancelScheduledSend(clientContext, sequenceNumber).ConfigureAwait(false);

                        return;
                    }

                    if (context.ScheduledEnqueueTimeUtc.HasValue)
                    {
                        var scheduled = await ScheduleSend(clientContext, context).ConfigureAwait(false);

                        if (scheduled)
                        {
                            return;
                        }
                    }

                    if (_context.SendObservers.Count > 0)
                    {
                        await _context.SendObservers.PreSend(context).ConfigureAwait(false);
                    }

                    var brokeredMessage = CreateBrokeredMessage(context);

                    await clientContext.Send(brokeredMessage).ConfigureAwait(false);

                    context.LogSent();

                    if (_context.SendObservers.Count > 0)
                    {
                        await _context.SendObservers.PostSend(context).ConfigureAwait(false);
                    }
                }
                catch (Exception ex)
                {
                    if (_context.SendObservers.Count > 0)
                    {
                        await _context.SendObservers.SendFault(context, ex).ConfigureAwait(false);
                    }

                    throw;
                }
                finally
                {
                    activity?.Stop();
                }
            }
Пример #30
0
        public void Configure(
            IApplicationBuilder app,
            IHostingEnvironment env,
            ILoggerFactory loggerFactory,
            IApplicationLifetime appLifetime)
        {
            var loggerConfiguration = new LoggerConfiguration().Enrich.FromLogContext();

            if (env.IsDevelopment())
            {
                loggerConfiguration
                .MinimumLevel.Debug()
                .WriteTo.ColoredConsole();
            }
            else
            {
                loggerConfiguration.MinimumLevel.Is(LogEventLevel.Verbose);

                var logGroupName = Configuration["aws:cloudwatch:logGroupName"] + "/" + env.EnvironmentName;

                AWSCredentials credentials =
                    new BasicAWSCredentials(Configuration["aws:accessKey"], Configuration["aws:secret"]);

                IAmazonCloudWatchLogs client = new AmazonCloudWatchLogsClient(credentials, RegionEndpoint.EUCentral1);
                var options = new CloudWatchSinkOptions
                {
                    LogGroupName          = logGroupName,
                    LogEventRenderer      = new JsonLogEventRenderer(),
                    MinimumLogEventLevel  = (LogEventLevel)Convert.ToInt32(Configuration["logLevel"]),
                    LogStreamNameProvider = new ConstantLogStreamNameProvider(Environment.MachineName)
                };

                loggerConfiguration.WriteTo.AmazonCloudWatch(options, client);
            }

            loggerConfiguration
            .WriteTo
            .Logger(lc =>
                    lc.Filter
                    .ByIncludingOnly($"EventId.Id = {LogEvents.Audit.Id}")
                    .WriteTo.File(Configuration["auditLog"],
                                  restrictedToMinimumLevel: LogEventLevel.Verbose,
                                  outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{IPAddress}] [{Level}] {Message}{NewLine}{Exception}"
                                  )
                    );

            var cgc = app.ApplicationServices.GetService <CollectionGameConfiguration>();

            loggerConfiguration
            .WriteTo
            .Logger(lc =>
                    lc.Filter
                    .ByIncludingOnly($"EventId.Id = {LogEvents.CollectionGame.Id}")
                    .WriteTo.File(cgc.LogFile, (LogEventLevel)cgc.LogLevel)
                    );

            Log.Logger = loggerConfiguration.CreateLogger();

            loggerFactory
            .WithFilter(new FilterLoggerSettings
            {
                { "Microsoft", env.IsDevelopment() ? LogLevel.Information : LogLevel.Warning },
                { "System", env.IsDevelopment() ? LogLevel.Information : LogLevel.Warning }
            })
            .AddSerilog();

            _logger = loggerFactory.CreateLogger(GetType());
            _logger.LogInformation($"Logging commences");

            appLifetime.ApplicationStopped.Register(Log.CloseAndFlush);

            app.UseCors("CorsPolicy");
            app.UseAuthentication();

            app.Use(async(context, next) =>
            {
                using (LogContext.PushProperty("IPAddress",
                                               context.Request.Headers.ContainsKey("X-Forwarded-For") ?
                                               context.Request.Headers["X-Forwarded-For"].ToString()
                        : context.Connection.RemoteIpAddress.ToString()))
                {
                    await next();
                }
            });

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    "default",
                    "{controller=Test}/{action=Index}/{id?}");
            });

            app.UseSwagger();

            app.UseSwaggerUI(c =>
            {
                c.RoutePrefix = "swagger/v2/ui";
                c.DocExpansion(DocExpansion.None);
                c.SwaggerEndpoint("/swagger/v2/swagger.json", "API v2");
                c.EnableDeepLinking();
            });

            if (env.IsProduction())
            {
                _logger.LogDebug("Starting JobManager to run jobs");
                JobManager.JobFactory = new ServiceProviderJobFactory(app.ApplicationServices);
                JobManager.Initialize(new JobRegistry(Configuration.GetSection("jobs")));
            }

            _logger.LogInformation($"Startup complete ({env.EnvironmentName})");
        }
Пример #31
0
        private void Update()
        {
            if (m_ResetLog == true)
            {
                m_ResetLog = false;
                m_LogContextMap.Clear();
                m_LogListLock.EnterWriteLock();
                try
                {
                    m_LogList.Clear();
                }
                finally
                {
                    m_LogListLock.ExitWriteLock();
                }
            }

            var deletedNameSet = new HashSet <string>(m_LogContextMap.Keys);

            m_LogDirectoryInfo.Refresh();

            if (m_LogDirectoryInfo.Exists == true)
            {
                var fileInfos = m_LogDirectoryInfo.GetFiles("output_log_*.txt", SearchOption.TopDirectoryOnly);

                // sort by creation time
                Array.Sort(fileInfos, (a, b) => a.CreationTimeUtc.CompareTo(b.CreationTimeUtc));

                var utcNow             = DateTime.UtcNow;
                var minLimitDateTime   = utcNow.AddDays(-7d);
                var minRefreshDateTime = utcNow.AddMinutes(-3d);

                foreach (var fileInfo in fileInfos)
                {
                    var lastWriteTimeUtc = fileInfo.LastWriteTimeUtc;

                    if (lastWriteTimeUtc < minLimitDateTime)
                    {
                        continue;
                    }

                    if (lastWriteTimeUtc >= minRefreshDateTime)
                    {
                        fileInfo.Refresh();
                        if (fileInfo.Exists == false)
                        {
                            continue;
                        }
                    }

                    if (m_LogContextMap.TryGetValue(fileInfo.Name, out LogContext logContext) == true)
                    {
                        deletedNameSet.Remove(fileInfo.Name);
                    }
                    else
                    {
                        logContext = new LogContext();
                        m_LogContextMap.Add(fileInfo.Name, logContext);
                    }

                    if (logContext.Length == fileInfo.Length)
                    {
                        continue;
                    }

                    logContext.Length = fileInfo.Length;
                    ParseLog(fileInfo, logContext);
                }
            }

            foreach (var name in deletedNameSet)
            {
                m_LogContextMap.Remove(name);
            }
        }
Пример #32
0
 /// <summary>
 /// Provider interface function for logging command lifecycle event
 /// </summary>
 /// <param name="logContext"></param>
 /// <param name="newState"></param>
 /// 
 internal static void LogCommandLifecycleEvent(LogContext logContext, CommandState newState)
 {
     provider.LogCommandLifecycleEvent(() => logContext, newState);
 }
Пример #33
0
 /// <summary>
 /// Provider interface function for logging provider health event
 /// </summary>
 /// <param name="logContext"></param>
 /// <param name="providerName"></param>
 /// <param name="exception"></param>
 internal static void LogProviderHealthEvent(LogContext logContext, string providerName, Exception exception)
 {
     provider.LogProviderHealthEvent(logContext, providerName, exception);
 }
Пример #34
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseMiddleware <ExceptionMiddleware>();

            // Adds an IP address to your log's context.
            app.Use(async(context, next) =>
            {
                using (LogContext.PushProperty("IPAddress", context.Connection.RemoteIpAddress))
                {
                    await next.Invoke();
                }
            });

            // Build your own authorization system or use Identity.
            app.Use(async(context, next) =>
            {
                var accountService = (AccountService)context.RequestServices.GetService(typeof(AccountService));
                var verifyResult   = accountService.Verify(context);
                if (!verifyResult.HasErrors)
                {
                    context.Items.Add(Constants.HttpContextServiceUserItemKey, verifyResult.Value);
                }
                await next.Invoke();
                // Do logging or other work that doesn't write to the Response.
            });

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
#pragma warning disable CS0618 // Type or member is obsolete
                // WebpackDevMiddleware.UseWebpackDevMiddleware(app, new WebpackDevMiddlewareOptions
                // {
                //     HotModuleReplacement = true,
                //     ReactHotModuleReplacement = true
                // });
#pragma warning restore CS0618 // Type or member is obsolete
            }
            else
            {
                app.UseExceptionHandler("/Main/Error");
                app.UseHsts();
            }

            app.UseDefaultFiles();
            app.UseStaticFiles();

            // Write streamlined request completion events, instead of the more verbose ones from the framework.
            // To use the default framework request logging instead, remove this line and set the "Microsoft"
            // level in appsettings.json to "Information".
            app.UseSerilogRequestLogging();

            app.UseRouting();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Main}/{action=Index}/{id?}");

                endpoints.MapFallbackToController("Index", "Main");
            });

            app.UseHttpsRedirection();
        }
Пример #35
0
    private void RemoveWorkflow(object parameter)
    {
        VersionManager verMan = VersionManager.GetInstance(Tree);
        TreeNode       node   = null;

        // Custom logging
        Tree.LogEvents         = false;
        Tree.AllowAsyncActions = false;
        CanceledString         = ResHelper.GetString("workflowdocuments.removingcanceled", currentCulture);
        try
        {
            // Begin log
            AddLog(ResHelper.GetString("content.preparingdocuments", currentCulture));

            string where = parameter as string;

            // Get the documents
            DataSet documents = GetDocumentsToProcess(where);

            if (!DataHelper.DataSourceIsEmpty(documents))
            {
                // Begin log
                AddLog(ResHelper.GetString("workflowdocuments.removingwf", currentCulture));

                foreach (DataTable classTable in documents.Tables)
                {
                    foreach (DataRow nodeRow in classTable.Rows)
                    {
                        // Get the current document
                        string className  = ValidationHelper.GetString(nodeRow["ClassName"], string.Empty);
                        string aliasPath  = ValidationHelper.GetString(nodeRow["NodeAliasPath"], string.Empty);
                        string docCulture = ValidationHelper.GetString(nodeRow["DocumentCulture"], string.Empty);
                        string siteName   = SiteInfoProvider.GetSiteName(nodeRow["NodeSiteID"].ToInteger(0));

                        // Get published version
                        node = Tree.SelectSingleNode(siteName, aliasPath, docCulture, false, className, false);
                        string encodedAliasPath = HTMLHelper.HTMLEncode(ValidationHelper.GetString(aliasPath, string.Empty) + " (" + node.GetValue("DocumentCulture") + ")");

                        // Destroy document history
                        verMan.DestroyDocumentHistory(node.DocumentID);

                        using (new CMSActionContext {
                            LogEvents = false
                        })
                        {
                            // Clear workflow
                            DocumentHelper.ClearWorkflowInformation(node);
                            node.Update();
                        }

                        // Add log record
                        AddLog(encodedAliasPath);

                        // Add record to eventlog
                        LogContext.LogEvent(EventType.INFORMATION, "Content", "REMOVEDOCWORKFLOW", string.Format(GetString("workflowdocuments.removeworkflowsuccess"), encodedAliasPath), RequestContext.RawURL, currentUser.UserID, currentUser.UserName, node.NodeID, node.GetDocumentName(), RequestContext.UserHostAddress, node.NodeSiteID, SystemContext.MachineName, RequestContext.URLReferrer, RequestContext.UserAgent, DateTime.Now);
                    }
                }
                CurrentInfo = GetString("workflowdocuments.removecomplete");
            }
            else
            {
                AddError(ResHelper.GetString("workflowdocuments.nodocumentstoclear", currentCulture));
            }
        }
        catch (ThreadAbortException ex)
        {
            if (CMSThread.Stopped(ex))
            {
                // When canceled
                CurrentInfo = CanceledString;
            }
            else
            {
                int siteId = (node != null) ? node.NodeSiteID : SiteContext.CurrentSiteID;
                // Log error
                LogExceptionToEventLog("REMOVEDOCWORKFLOW", "workflowdocuments.removefailed", ex, siteId);
            }
        }
        catch (Exception ex)
        {
            int siteId = (node != null) ? node.NodeSiteID : SiteContext.CurrentSiteID;
            // Log error
            LogExceptionToEventLog("REMOVEDOCWORKFLOW", "workflowdocuments.removefailed", ex, siteId);
        }
    }
Пример #36
0
        static void PushHeaderProperty(string headerKey, IMessageContext ctx, string loggerKey)
        {
            var propertyDisposer = LogContext.PushProperty(loggerKey, ctx.Headers[headerKey]);

            ctx.Disposed += propertyDisposer.Dispose;
        }
Пример #37
0
            public async Task Send(ModelContext modelContext)
            {
                LogContext.SetCurrentIfNull(_context.LogContext);

                await _context.ConfigureTopologyPipe.Send(modelContext).ConfigureAwait(false);

                var properties = modelContext.Model.CreateBasicProperties();

                var context = new BasicPublishRabbitMqSendContext <T>(properties, _context.Exchange, _message, _cancellationToken);

                await _pipe.Send(context).ConfigureAwait(false);

                var exchange = context.Exchange;

                if (exchange.Equals(RabbitMqExchangeNames.ReplyTo))
                {
                    if (string.IsNullOrWhiteSpace(context.RoutingKey))
                    {
                        throw new TransportException(context.DestinationAddress, "RoutingKey must be specified when sending to reply-to address");
                    }

                    exchange = "";
                }

                var activity = LogContext.IfEnabled(OperationName.Transport.Send)?.StartSendActivity(context);

                try
                {
                    if (_context.SendObservers.Count > 0)
                    {
                        await _context.SendObservers.PreSend(context).ConfigureAwait(false);
                    }

                    byte[] body = context.Body;

                    if (context.TryGetPayload(out PublishContext publishContext))
                    {
                        context.Mandatory = context.Mandatory || publishContext.Mandatory;
                    }

                    properties.Headers ??= new Dictionary <string, object>();

                    properties.ContentType = context.ContentType.MediaType;

                    properties.Headers["Content-Type"] = context.ContentType.MediaType;

                    SetHeaders(properties.Headers, context.Headers);

                    properties.Persistent = context.Durable;

                    if (context.MessageId.HasValue)
                    {
                        properties.MessageId = context.MessageId.ToString();
                    }

                    if (context.CorrelationId.HasValue)
                    {
                        properties.CorrelationId = context.CorrelationId.ToString();
                    }

                    if (context.TimeToLive.HasValue)
                    {
                        properties.Expiration = (context.TimeToLive > TimeSpan.Zero ? context.TimeToLive.Value : TimeSpan.FromSeconds(1)).TotalMilliseconds
                                                .ToString("F0", CultureInfo.InvariantCulture);
                    }

                    if (context.RequestId.HasValue && (context.ResponseAddress?.AbsolutePath?.EndsWith(RabbitMqExchangeNames.ReplyTo) ?? false))
                    {
                        context.BasicProperties.ReplyTo = RabbitMqExchangeNames.ReplyTo;
                    }

                    var publishTask = modelContext.BasicPublishAsync(exchange, context.RoutingKey ?? "", context.Mandatory, context.BasicProperties, body,
                                                                     context.AwaitAck);

                    await publishTask.OrCanceled(context.CancellationToken).ConfigureAwait(false);

                    context.LogSent();

                    if (_context.SendObservers.Count > 0)
                    {
                        await _context.SendObservers.PostSend(context).ConfigureAwait(false);
                    }
                }
                catch (Exception ex)
                {
                    context.LogFaulted(ex);

                    if (_context.SendObservers.Count > 0)
                    {
                        await _context.SendObservers.SendFault(context, ex).ConfigureAwait(false);
                    }

                    throw;
                }
                finally
                {
                    activity?.Stop();
                }
            }
Пример #38
0
    private static void Main()
    {
        Log.Logger = new LoggerConfiguration()
                     .Enrich.FromLogContext()
                     .MinimumLevel.Debug()
                     .WriteTo.Console()
                     // Other overloads exist, for example, configure the SDK with only the DSN or no parameters at all.
                     .WriteTo.Sentry(o =>
        {
            o.MinimumBreadcrumbLevel = LogEventLevel.Debug; // Debug and higher are stored as breadcrumbs (default os Information)
            o.MinimumEventLevel      = LogEventLevel.Error; // Error and higher is sent as event (default is Error)
            // If DSN is not set, the SDK will look for an environment variable called SENTRY_DSN. If nothing is found, SDK is disabled.
            o.Dsn = new Dsn("https://[email protected]/5428537");
            o.AttachStacktrace = true;
            o.SendDefaultPii   = true;   // send PII like the username of the user logged in to the device
            // Other configuration
        })
                     .CreateLogger();

        try
        {
            // The following anonymous object gets serialized and sent with log messages
            using (LogContext.PushProperty("inventory", new
            {
                SmallPotion = 3,
                BigPotion = 0,
                CheeseWheels = 512
            }))
            {
                // Minimum Breadcrumb and Event log levels are set to levels higher than Verbose
                // In this case, Verbose messages are ignored
                Log.Verbose("Verbose message which is not sent.");

                // Minimum Breadcrumb level is set to Debug so the following message is stored in memory
                // and sent with following events of the same Scope
                Log.Debug("Debug message stored as breadcrumb.");

                // Sends an event and stores the message as a breadcrumb too, to be sent with any upcoming events.
                Log.Error("Some event that includes the previous breadcrumbs");

                try
                {
                    DoWork();
                }
                catch (Exception e)
                {
                    e.Data.Add("details", "Do work always throws.");
                    Log.Fatal(e, "Error: with exception");
                    throw;
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
        finally
        {
            Log.CloseAndFlush();
        }
    }
Пример #39
0
        public static void PushProperty <T>(string name, T propValue, bool destructureObjects = false)
        {
            Log.Logger.ForContext(name, propValue);

            LogContext.PushProperty(name, propValue, destructureObjects);
        }
    /// <summary>
    /// Ensures and returns the log context for the async control.
    /// </summary>
    private LogContext EnsureAsyncLogContext()
    {
        var log = LogContext.EnsureLog(ucAsync.ProcessGUID);

        return(log);
    }
Пример #41
0
        private bool ParseLogOnPlayerJoinedOrLeft(FileInfo fileInfo, LogContext logContext, string line, int offset)
        {
            // 2020.10.31 23:36:58 Log        -  [NetworkManager] OnPlayerJoined pypy
            // 2020.10.31 23:36:58 Log        -  [Player] Initialized PlayerAPI "pypy" is local
            // 2020.10.31 23:36:58 Log        -  [NetworkManager] OnPlayerJoined Rize♡
            // 2020.10.31 23:36:58 Log        -  [Player] Initialized PlayerAPI "Rize♡" is remote

            // 2020.11.01 00:07:01 Log        -  [NetworkManager] OnPlayerLeft Rize♡
            // 2020.11.01 00:07:01 Log        -  [PlayerManager] Removed player 2 / Rize♡
            // 2020.11.01 00:07:02 Log        -  [Player] Unregistering Rize♡

            if (string.Compare(line, offset, "Initialized PlayerAPI \"", 0, 23, StringComparison.Ordinal) == 0)
            {
                var pos = line.LastIndexOf("\" is ");
                if (pos < 0)
                {
                    return(false);
                }

                var userDisplayName = line.Substring(offset + 23, pos - (offset + 23));
                var userType        = line.Substring(pos + 5);

                AppendLog(new[]
                {
                    fileInfo.Name,
                    ConvertLogTimeToISO8601(line),
                    "player-joined",
                    userDisplayName,
                    userType,
                });

                return(true);
            }

            // fallback method

            /*if (string.Compare(line, offset, "OnPlayerJoined ", 0, 15, StringComparison.Ordinal) == 0)
             * {
             *  var userDisplayName = line.Substring(offset + 15);
             *
             *  AppendLog(new[]
             *  {
             *      fileInfo.Name,
             *      ConvertLogTimeToISO8601(line),
             *      "player-joined",
             *      userDisplayName
             *  });
             *
             *  return true;
             * }*/

            if (string.Compare(line, offset, "OnPlayerLeft ", 0, 13, StringComparison.Ordinal) == 0)
            {
                var userDisplayName = line.Substring(offset + 13);

                AppendLog(new[]
                {
                    fileInfo.Name,
                    ConvertLogTimeToISO8601(line),
                    "player-left",
                    userDisplayName
                });

                return(true);
            }

            return(false);
        }
        static void Main(string[] args)
        {
            var configBuilder = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

            _configuration = configBuilder.Build();

            var logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .WriteTo.ColoredConsole()
                         .CreateLogger();
            ILoggerFactory loggerFactory = new LoggerFactory();

            loggerFactory.AddSerilog(logger);
            LogContext.ConfigureCurrentLogContext(loggerFactory);

            var smsConfiguration = new SmsConfiguration
            {
                BaseUrl          = _configuration["BaseUrl"],
                SmsSender        = _configuration["SmsSender"],
                RapidProPassword = _configuration["RapidProPassword"],
                RapidProUserName = _configuration["RapidProUserName"],
                RapidProSmsCode  = _configuration["RapidProSmsCode"]
            };

            var builder = new ContainerBuilder();

            builder.RegisterModule(new ServiceModule(smsConfiguration));
            builder.RegisterModule <ConsumersModule>();
            builder.Register(context =>
            {
                var busControl = Bus.Factory.CreateUsingRabbitMq(config =>
                {
                    config.ConfigureJsonSerializer(options =>
                    {
                        options.DefaultValueHandling = DefaultValueHandling.Include;
                        return(options);
                    });
                    var host = config.Host(new Uri(_configuration.GetValue <string>("RabbitMQHost")), h =>
                    {
                        h.Username(_configuration.GetValue <string>("RabbitMQUsername"));
                        h.Password(_configuration.GetValue <string>("RabbitMQPassword"));
                    });
                    config.PrefetchCount = 32;
                    config.UseRetry(retry => retry.Interval(3, TimeSpan.FromSeconds(6)));
                    config.ReceiveEndpoint(_configuration["SmsQueue"], e =>
                    {
                        e.Consumer <SmsConsumer>(context);
                    });
                });
                return(busControl);
            })
            .SingleInstance()
            .As <IBusControl>()
            .As <IBus>();
            LogContext.Info?.Log("Creating Service bus..");
            var container = builder.Build();
            var bus       = container.Resolve <IBusControl>();

            bus.Start();
            LogContext.Info?.Log("Bus started");
            LogContext.Info?.Log("Waiting for request");
            Console.ReadLine();
            bus.Stop();
        }
Пример #43
0
        /// <summary>
        /// Adds Sejil to the request pipeline.
        /// </summary>
        /// <param name="app">The application builder.</param>
        /// <returns></returns>
        public static IApplicationBuilder UseSejil(this IApplicationBuilder app)
        {
            var settings = (ISejilSettings)app.ApplicationServices.GetService(typeof(ISejilSettings));
            var url      = settings.Url.Trim('/'); //settings.Url.Substring(1); // Skip the '/'

            app.Use(async(context, next) =>
            {
                var userName = context.User.Identity.IsAuthenticated
                    ? context.User.Identity.Name
                    : context.Connection.RemoteIpAddress?.ToString() ?? "Unknown";
                using (LogContext.PushProperty("Username", userName))
                {
                    await next.Invoke();
                }
            });

            app.UseRouter(routes =>
            {
                routes.MapGet(url, async context =>
                {
                    var controller = GetSejilController(context);
                    await controller.GetIndexAsync();
                });

                routes.MapPost($"{url}/events", async context =>
                {
                    var query = await JsonSerializer.DeserializeAsync <LogQueryFilter>(context.Request.Body, _camelCaseJson);
                    Int32.TryParse(context.Request.Query["page"].FirstOrDefault(), out var page);
                    Int32.TryParse(context.Request.Query["pageSize"].FirstOrDefault(), out var pageSize);
                    var dateParsed = DateTime.TryParse(context.Request.Query["startingTs"].FirstOrDefault(), out var startingTs);

                    var controller = GetSejilController(context);
                    await controller.GetEventsAsync(page, pageSize, dateParsed ? startingTs : (DateTime?)null, query);
                });

                routes.MapPost($"{url}/log-query", async context =>
                {
                    var logQuery = await JsonSerializer.DeserializeAsync <LogQuery>(context.Request.Body, _camelCaseJson);

                    var controller = GetSejilController(context);
                    await controller.SaveQueryAsync(logQuery);
                });

                routes.MapGet($"{url}/log-queries", async context =>
                {
                    var controller = GetSejilController(context);
                    await controller.GetQueriesAsync();
                });

                routes.MapGet($"{url}/min-log-level", async context =>
                {
                    var controller = GetSejilController(context);
                    await controller.GetMinimumLogLevelAsync();
                });

                routes.MapGet($"{url}/user-name", async context =>
                {
                    var controller = GetSejilController(context);
                    await controller.GetUserNameAsync();
                });

                routes.MapPost($"{url}/min-log-level", async context =>
                {
                    var minLogLevel = await GetRequestBodyAsync(context.Request);
                    var controller  = GetSejilController(context);
                    controller.SetMinimumLogLevel(minLogLevel);
                });

                routes.MapPost($"{url}/del-query", async context =>
                {
                    var queryName  = await GetRequestBodyAsync(context.Request);
                    var controller = GetSejilController(context);
                    await controller.DeleteQueryAsync(queryName);
                });

                routes.MapGet($"{url}/title", async context =>
                {
                    var controller = GetSejilController(context);
                    await controller.GetTitleAsync();
                });
            });

            return(app);
        }
Пример #44
0
        public HttpResponseMessage List(RequestDTO req)
        {
            try
            {
                OpenContentModuleConfig module = OpenContentModuleConfig.Create(ActiveModule, PortalSettings);
                JObject reqOptions             = null;
                if (!string.IsNullOrEmpty(req.options))
                {
                    reqOptions = JObject.Parse(req.options);
                }
                if (module.IsListMode())
                {
                    var          indexConfig  = OpenContentUtils.GetIndexConfig(module.Settings.Template);
                    QueryBuilder queryBuilder = new QueryBuilder(indexConfig);
                    bool         isEditable   = module.ViewModule.CheckIfEditable(module);
                    queryBuilder.Build(module.Settings.Query, !isEditable, UserInfo.UserID, DnnLanguageUtils.GetCurrentCultureCode(), UserInfo.Social.Roles.FromDnnRoles());

                    JplistQueryBuilder.MergeJpListQuery(indexConfig, queryBuilder.Select, req.StatusLst, DnnLanguageUtils.GetCurrentCultureCode());
                    IDataItems dsItems;
                    if (queryBuilder.DefaultNoResults && queryBuilder.Select.IsEmptyQuery)
                    {
                        dsItems = new DefaultDataItems()
                        {
                            Items = new List <DefaultDataItem>(),
                            Total = 0
                        };
                    }
                    else
                    {
                        IDataSource ds        = DataSourceManager.GetDataSource(module.Settings.Manifest.DataSource);
                        var         dsContext = OpenContentUtils.CreateDataContext(module, UserInfo.UserID, false, reqOptions);
                        dsItems = ds.GetAll(dsContext, queryBuilder.Select);
                    }
                    var mf = new ModelFactoryMultiple(dsItems.Items, module);
                    mf.Options = reqOptions;
                    var model = mf.GetModelAsJson(false, req.onlyItems);

                    //model["luceneQuery"] = dsItems.DebugInfo;
                    if (LogContext.IsLogActive)
                    {
                        LogContext.Log(ActiveModule.ModuleID, "RequestContext", "IsEditable", isEditable);
                        LogContext.Log(ActiveModule.ModuleID, "RequestContext", "UserRoles", PortalSettings.UserInfo.Social.Roles.Select(r => r.RoleName));
                        LogContext.Log(ActiveModule.ModuleID, "RequestContext", "CurrentUserId", PortalSettings.UserId);
                        var logKey = "Query";
                        LogContext.Log(ActiveModule.ModuleID, logKey, "select", queryBuilder.Select);
                        LogContext.Log(ActiveModule.ModuleID, logKey, "debuginfo", dsItems.DebugInfo);
                        LogContext.Log(ActiveModule.ModuleID, logKey, "model", model);
                        model["Logs"] = JToken.FromObject(LogContext.Current.ModuleLogs(ActiveModule.ModuleID));
                    }
                    var res = new ResultDTO()
                    {
                        data  = model,
                        count = dsItems.Total
                    };
                    return(Request.CreateResponse(HttpStatusCode.OK, res));
                }
                else
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "not supported because not in multi items template "));
                }
            }
            catch (Exception exc)
            {
                App.Services.Logger.Error(exc);
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc));
            }
        }
Пример #45
0
        protected override void InternalExecute()
        {
            if (_config == null)
            {
                throw new Exception("You must call Configure() first");
            }
            var workItemServer = Engine.Source.GetService <WorkItemServer>();

            workItemLinkEnricher  = Services.GetRequiredService <WorkItemLinkEnricher>();
            attachmentEnricher    = new AttachmentMigrationEnricher(workItemServer, _config.AttachmentWorkingPath, _config.AttachmentMaxSize);
            embededImagesEnricher = new EmbededImagesRepairEnricher();
            gitRepositoryEnricher = new GitRepositoryEnricher(Engine);
            nodeStructureEnricher = new NodeStructureEnricher(Engine);
            VssClientCredentials adoCreds = new VssClientCredentials();

            _witClient = new WorkItemTrackingHttpClient(Engine.Target.Config.Collection, adoCreds);
            //Validation: make sure that the ReflectedWorkItemId field name specified in the config exists in the target process, preferably on each work item type.
            ConfigValidation();
            PopulateIgnoreList();

            nodeStructureEnricher.MigrateAllNodeStructures(_config.PrefixProjectToNodes, _config.NodeBasePaths);

            var stopwatch = Stopwatch.StartNew();
            //////////////////////////////////////////////////
            string sourceQuery =
                string.Format(
                    @"SELECT [System.Id], [System.Tags] FROM WorkItems WHERE [System.TeamProject] = @TeamProject {0} ORDER BY {1}",
                    _config.WIQLQueryBit, _config.WIQLOrderBit);
            var sourceWorkItems = Engine.Source.WorkItems.GetWorkItems(sourceQuery);

            contextLog.Information("Replay all revisions of {sourceWorkItemsCount} work items?", sourceWorkItems.Count);
            //////////////////////////////////////////////////
            contextLog.Information("Found target project as {@destProject}", Engine.Target.WorkItems.Project.Name);
            //////////////////////////////////////////////////////////FilterCompletedByQuery
            if (_config.FilterWorkItemsThatAlreadyExistInTarget)
            {
                sourceWorkItems = FilterWorkItemsThatAlreadyExistInTarget(sourceWorkItems);
            }
            //////////////////////////////////////////////////
            _current       = 1;
            _count         = sourceWorkItems.Count;
            _elapsedms     = 0;
            _totalWorkItem = sourceWorkItems.Count;
            foreach (WorkItemData sourceWorkItemData in sourceWorkItems)
            {
                var sourceWorkItem = sourceWorkItemData.ToWorkItem();
                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");
                                                break;
                                            }
                                        }
                                    }
            }
            //////////////////////////////////////////////////
            stopwatch.Stop();

            contextLog.Information("DONE in {Elapsed}", stopwatch.Elapsed.ToString("c"));
        }
Пример #46
0
 protected static void BaseClassInitialize(TestContext testContext)
 {
     _testClassContext = LogContext.PushProperty("TestClass", testContext.FullyQualifiedTestClassName);
 }
Пример #47
0
        async Task IBrokeredMessageReceiver.Handle(Message message, Action <ReceiveContext> contextCallback)
        {
            LogContext.Current = _context.LogContext;

            var context = new ServiceBusReceiveContext(message, _context);

            contextCallback?.Invoke(context);

            context.TryGetPayload <MessageLockContext>(out var lockContext);

            var activity = LogContext.IfEnabled(OperationName.Transport.Receive)?.StartReceiveActivity(context);

            try
            {
                if (_context.ReceiveObservers.Count > 0)
                {
                    await _context.ReceiveObservers.PreReceive(context).ConfigureAwait(false);
                }

                if (message.SystemProperties.LockedUntilUtc <= DateTime.UtcNow)
                {
                    throw new MessageLockExpiredException(_inputAddress, $"The message lock expired: {message.MessageId}");
                }

                if (message.ExpiresAtUtc < DateTime.UtcNow)
                {
                    throw new MessageTimeToLiveExpiredException(_inputAddress, $"The message TTL expired: {message.MessageId}");
                }

                await _context.ReceivePipe.Send(context).ConfigureAwait(false);

                await context.ReceiveCompleted.ConfigureAwait(false);

                if (lockContext != null)
                {
                    await lockContext.Complete().ConfigureAwait(false);
                }

                if (_context.ReceiveObservers.Count > 0)
                {
                    await _context.ReceiveObservers.PostReceive(context).ConfigureAwait(false);
                }
            }
            catch (SessionLockLostException ex)
            {
                LogContext.Warning?.Log(ex, "Session Lock Lost: {MessageId}", message.MessageId);

                if (_context.ReceiveObservers.Count > 0)
                {
                    await _context.ReceiveObservers.ReceiveFault(context, ex).ConfigureAwait(false);
                }
            }
            catch (MessageLockLostException ex)
            {
                LogContext.Warning?.Log(ex, "Session Lock Lost: {MessageId}", message.MessageId);

                if (_context.ReceiveObservers.Count > 0)
                {
                    await _context.ReceiveObservers.ReceiveFault(context, ex).ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                if (_context.ReceiveObservers.Count > 0)
                {
                    await _context.ReceiveObservers.ReceiveFault(context, ex).ConfigureAwait(false);
                }

                if (lockContext == null)
                {
                    throw;
                }

                try
                {
                    await lockContext.Abandon(ex).ConfigureAwait(false);
                }
                catch (Exception exception)
                {
                    LogContext.Warning?.Log(exception, "Abandon message faulted: {MessageId}", message.MessageId);
                }
            }
            finally
            {
                activity?.Stop();

                context.Dispose();
            }
        }
    /// <summary>
    /// Refreshes the security parameters in macros for all the objects of the specified object types.
    /// Signs all the macros with the current user if the old salt is not specified.
    /// </summary>
    /// <param name="objectTypes">Object types</param>
    /// <param name="oldSalt">Old salt </param>
    /// <param name="newSalt">New salt</param>
    private void RefreshSecurityParams(IEnumerable <string> objectTypes, string oldSalt, string newSalt)
    {
        var oldSaltSpecified = !string.IsNullOrEmpty(oldSalt) && !chkRefreshAll.Checked;
        var newSaltSpecified = !string.IsNullOrEmpty(newSalt) && !chkUseCurrentSalt.Checked;

        processedObjects.Clear();

        using (CMSActionContext context = new CMSActionContext())
        {
            context.LogEvents          = false;
            context.LogSynchronization = false;

            foreach (var objectType in objectTypes)
            {
                var objectTypeResourceKey = TypeHelper.GetObjectTypeResourceKey(objectType);
                var niceObjectType        = GetString(objectTypeResourceKey);
                if (niceObjectType == objectTypeResourceKey)
                {
                    if (objectType.StartsWithCSafe("bizformitem.bizform.", true))
                    {
                        DataClassInfo dci = DataClassInfoProvider.GetDataClassInfo(objectType.Substring("bizformitem.".Length));
                        if (dci != null)
                        {
                            niceObjectType = "on-line form " + dci.ClassDisplayName;
                        }
                    }
                    else
                    {
                        niceObjectType = objectType;
                    }
                }

                LogContext.AppendLine(string.Format(GetString("macros.refreshsecurityparams.processing"), niceObjectType));

                try
                {
                    var infos = new InfoObjectCollection(objectType);

                    foreach (var info in infos)
                    {
                        try
                        {
                            bool refreshed = false;
                            if (oldSaltSpecified)
                            {
                                refreshed = MacroSecurityProcessor.RefreshSecurityParameters(info, oldSalt, newSaltSpecified ? newSalt : ValidationHelper.HashStringSalt, true);
                            }
                            else
                            {
                                if (chkRefreshAll.Checked && newSaltSpecified)
                                {
                                    // Do not check integrity, but use new salt
                                    refreshed = MacroSecurityProcessor.RefreshSecurityParameters(info, MembershipContext.AuthenticatedUser.UserName, true, newSalt);
                                }
                                else
                                {
                                    // Do not check integrity, sign everything with current user
                                    refreshed = MacroSecurityProcessor.RefreshSecurityParameters(info, MembershipContext.AuthenticatedUser.UserName, true);
                                }
                            }

                            if (refreshed)
                            {
                                var objectName = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(info.Generalized.ObjectDisplayName));
                                processedObjects.Add(niceObjectType, objectName);
                            }
                        }
                        catch (Exception ex)
                        {
                            string message = "Signing " + TypeHelper.GetNiceObjectTypeName(info.ObjectType) + " " + info.Generalized.ObjectDisplayName + " failed: " + ex.Message;
                            EventLogProvider.LogEvent(EventType.ERROR, "Import", "MACROSECURITY", message);
                        }
                    }
                }
                catch (Exception e)
                {
                    LogContext.AppendLine(e.Message);
                    EventLogProvider.LogException(EVENTLOG_SOURCE_REFRESHSECURITYPARAMS, "ERROR", e);
                }
            }
        }

        EventLogProvider.LogEvent(EventType.INFORMATION, EVENTLOG_SOURCE_REFRESHSECURITYPARAMS, "PROCESSEDOBJECTS", eventDescription: GetProcessedObjectsForEventLog());
    }
Пример #49
0
 /// <summary>
 /// Provider interface function for logging engine lifecycle event
 /// </summary>
 /// <param name="logContext"></param>
 /// <param name="newState"></param>
 /// <param name="previousState"></param>
 /// 
 internal static void LogEngineLifecycleEvent(LogContext logContext, EngineState newState, EngineState previousState)
 {
     provider.LogEngineLifecycleEvent(logContext, newState, previousState);
 }
Пример #50
0
 /// <summary>
 /// When exception occurs, log it to event log.
 /// </summary>
 /// <param name="eventCode">Code of event</param>
 /// <param name="errorTitle">Message to log to asynchronous log</param>
 /// <param name="ex">Exception to log</param>
 /// <param name="siteId">ID of site</param>
 private void LogExceptionToEventLog(string eventCode, string errorTitle, Exception ex, int siteId)
 {
     AddError(ResHelper.GetString(errorTitle, currentCulture) + ": " + ex.Message);
     LogContext.LogEvent(EventType.ERROR, "Content", eventCode, EventLogProvider.GetExceptionLogMessage(ex), RequestContext.RawURL, currentUser.UserID, currentUser.UserName, 0, null, RequestContext.UserHostAddress, siteId, SystemContext.MachineName, RequestContext.URLReferrer, RequestContext.UserAgent, DateTime.Now);
 }
Пример #51
0
        /// <summary>
        /// Log context and exception
        /// </summary>
        /// <param name="context"></param>
        /// <param name="exception"></param>
        public void LogData(NancyContext context, Exception exception)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var statusCode = context.GetStatusCode(exception);

            string exceptionMessage    = null;
            string exceptionStackTrace = null;

            if (exception != null)
            {
                exceptionMessage    = HandleFieldSize(exception.Message, ExceptionMaxLenghtExtension.ErrorMessageLenght);
                exceptionStackTrace = HandleFieldSize(exception.StackTrace, ExceptionMaxLenghtExtension.ErrorExceptionLenght);
            }

            object controller = "Unknow";
            object action     = "Unknow";

            if (context.Items != null)
            {
                context.Items.TryGetValue("Controller", out controller);
                context.Items.TryGetValue("Action", out action);
            }

            LogContext.PushProperty("RequestBody", context.GetRequestBody(this.NancySerilogConfiguration.Blacklist));
            LogContext.PushProperty("Method", context.Request.Method);
            LogContext.PushProperty("Path", context.Request.Path);
            LogContext.PushProperty("Host", context.Request.Url.HostName);
            LogContext.PushProperty("Port", context.Request.Url.Port);
            LogContext.PushProperty("Url", context.Request.Url);
            LogContext.PushProperty("QueryString", context.Request.Url.Query);
            LogContext.PushProperty("Query", context.GetQueryString());
            LogContext.PushProperty("RequestHeaders", context.GetRequestHeaders());
            LogContext.PushProperty("Ip", context.GetIp());
            LogContext.PushProperty("IsSuccessful", statusCode < 400);
            LogContext.PushProperty("StatusCode", statusCode);
            LogContext.PushProperty("StatusDescription", ((HttpStatusCode)statusCode).ToString());
            LogContext.PushProperty("StatusCodeFamily", context.GetStatusCodeFamily(exception));
            LogContext.PushProperty("ProtocolVersion", context.Request.ProtocolVersion);
            LogContext.PushProperty("ErrorException", exceptionStackTrace);
            LogContext.PushProperty("ErrorMessage", exceptionMessage);
            LogContext.PushProperty("ResponseContent", context.GetResponseContent());
            LogContext.PushProperty("ContentType", context.Response.ContentType);
            LogContext.PushProperty("ContentLength", context.GetResponseLength());
            LogContext.PushProperty("ResponseHeaders", context.GetResponseHeaders());
            LogContext.PushProperty("ElapsedMilliseconds", context.GetExecutionTime());
            LogContext.PushProperty("Version", this.NancySerilogConfiguration.Version);
            LogContext.PushProperty("RequestKey", context.GetRequestKey());
            LogContext.PushProperty("Controller", controller?.ToString());
            LogContext.PushProperty("Operation", action?.ToString());
            LogContext.PushProperty("Environment", Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"));

            if (context.Items.ContainsKey("NancySerilogAdditionalInfo"))
            {
                var additionalInfo = (AdditionalInfo)context.Items["NancySerilogAdditionalInfo"];

                if (additionalInfo?.Data != null)
                {
                    foreach (var item in additionalInfo.Data)
                    {
                        LogContext.PushProperty(item.Key, item.Value);
                    }
                }
            }



            if (exception != null || statusCode >= 500)
            {
                var errorTitle = this.NancySerilogConfiguration.ErrorTitle ?? DefaultErrorTitle;
                this.NancySerilogConfiguration.Logger.Error(errorTitle);
            }
            else
            {
                var informationTitle = this.NancySerilogConfiguration.InformationTitle ?? DefaultInformationTitle;
                this.NancySerilogConfiguration.Logger.Information(informationTitle);
            }
        }
Пример #52
0
 public static void EnrichWithHttpRequest(this ILogger log, HttpRequest request)
 {
     LogContext.PushProperty(RequestConstants.CorrelationId, request.CorrelationId());
     LogContext.PushProperty(RequestConstants.CausationId, request.CausationId());
     LogContext.PushProperty(RequestConstants.RequestId, request.RequestId());
 }
Пример #53
0
 /// <summary>
 /// Provider interface function for logging health event
 /// </summary>
 /// <param name="logContext"></param>
 /// <param name="eventId"></param>
 /// <param name="exception"></param>
 /// <param name="additionalInfo"></param>
 /// 
 internal static void LogEngineHealthEvent(LogContext logContext, int eventId, Exception exception, Dictionary<String, String> additionalInfo)
 {
     provider.LogEngineHealthEvent(logContext, eventId, exception, additionalInfo);
 }
Пример #54
0
 public LogRepository(LogContext context)
 {
     _context = context;
 }
Пример #55
0
 /// <summary>
 /// Provider interface function for logging command health event
 /// </summary>
 /// <param name="logContext"></param>
 /// <param name="exception"></param>
 internal static void LogCommandHealthEvent(LogContext logContext, Exception exception)
 {
     provider.LogCommandHealthEvent(logContext, exception);
 }
Пример #56
0
 /// <summary>
 /// Writes a single event.
 /// </summary>
 /// <param name="id">Event id.</param>
 /// <param name="channel"></param>
 /// <param name="opcode"></param>
 /// <param name="task"></param>
 /// <param name="logContext">Log context.</param>
 /// <param name="payLoad"></param>
 internal void WriteEvent(PSEventId id, PSChannel channel, PSOpcode opcode, PSTask task, LogContext logContext, string payLoad)
 {
     WriteEvent(id, channel, opcode, GetPSLevelFromSeverity(logContext.Severity), task, (PSKeyword)0x0,
                LogContextToString(logContext), GetPSLogUserData(logContext.ExecutionContext), payLoad);
 }
Пример #57
0
 /// <summary>
 /// Provider interface function for logging pipeline execution detail.
 /// </summary>
 /// <param name="logContext"></param>
 /// <param name="pipelineExecutionDetail"></param>
 internal static void LogPipelineExecutionDetailEvent(LogContext logContext, List<String> pipelineExecutionDetail)
 {
     provider.LogPipelineExecutionDetailEvent(logContext, pipelineExecutionDetail);
 }
Пример #58
0
 /// <summary>
 /// Provider interface function for logging provider health event
 /// </summary>
 /// <param name="logContext"></param>
 /// <param name="providerName"></param>
 /// <param name="exception"></param>
 internal static void LogProviderHealthEvent(LogContext logContext, string providerName, Exception exception)
 {
     provider.LogProviderHealthEvent(logContext, providerName, exception);
 }
Пример #59
0
 /// <summary>
 /// Provider interface function for logging provider lifecycle event
 /// </summary>
 /// <param name="logContext"></param>
 /// <param name="providerName"></param>
 /// <param name="newState"></param>
 /// 
 internal static void LogProviderLifecycleEvent(LogContext logContext, string providerName, ProviderState newState)
 {
     provider.LogProviderLifecycleEvent(logContext, providerName, newState);
 }
Пример #60
0
 /// <summary>
 /// Provider interface function for logging provider lifecycle event
 /// </summary>
 /// <param name="logContext"></param>
 /// <param name="providerName"></param>
 /// <param name="newState"></param>
 ///
 internal static void LogProviderLifecycleEvent(LogContext logContext, string providerName, ProviderState newState)
 {
     provider.LogProviderLifecycleEvent(logContext, providerName, newState);
 }