public static void SetupLogConfiguration(string[] args) { var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); try { logger.Debug("init main function"); var accessKey = Environment.GetEnvironmentVariable(EnvironmentSettings.CW_ACCESS_KEY); var secretKey = Environment.GetEnvironmentVariable(EnvironmentSettings.CW_SECRET_KEY); var config = new LoggingConfiguration(); var awsTarget = new AWSTarget() { LogGroup = "NLog.Config", Region = "us-east-2", Credentials = new Amazon.Runtime.BasicAWSCredentials(accessKey, secretKey) }; config.AddTarget("aws", awsTarget); config.LoggingRules.Add(new LoggingRule("*", GetLogLevel(), awsTarget)); LogManager.Configuration = config; LogManager.Configuration.Variables["minLevel"] = Environment.GetEnvironmentVariable(EnvironmentSettings.LOG_MIN_LEVEL); LogManager.ReconfigExistingLoggers(); CreateWebHostBuilder(args).Build().Run(); } catch (Exception ex) { logger.Error(ex, "Error in init"); throw; } finally { LogManager.Shutdown(); } }
private AWSTarget CreateAwsTarget(string logGroup, string region) { var target = new AWSTarget(); target.Credentials = new BasicAWSCredentials(Environment.GetEnvironmentVariable("AccessKeyId"), Environment.GetEnvironmentVariable("SecretKeyId")); target.LogGroup = logGroup; target.Region = region; var format = "{" + "Id=" + "${event-properties:item=idlog}" + '\'' + ", LogTimeStamp='" + "${longdate}" + '\'' + ", MachineName='" + "${aspnet-request-ip}" + '\'' + ", Level='" + "${level}" + '\'' + ", Message='" + "${message}" + ", Exception='" + "${stacktrace}" + ", Payload='" + "${when:when='${aspnet-request-method}' == 'GET':inner='${aspnet-request-querystring}':else='${aspnet-request-posted-body}'}" + '\'' + ", CallSite='" + "${aspnet-request-url:IncludePort=true:IncludeQueryString=true}" + '\'' + ", Action='" + "${aspnet-request-method}" + '\'' + ", Username='******'\'' + ", MethodName='" + "${event-properties:item=methodName}" + '\'' + ", ApplicationName='" + "Test" + "}"; target.LogStreamNameSuffix = "Demo"; target.LogStreamNamePrefix = "Logger"; target.Layout = format; return(target); }
public static void ConfigureNLog() { // Just a Config to access to AWS CloudWatch var config = new LoggingConfiguration(); var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); var awsTarget = new AWSTarget() { LogGroup = "NeokyGroup", Region = "eu-west-2", Credentials = new BasicAWSCredentials(Constants.AWS_ACCESS_KEY_ID, Constants.AWS_SECRET_ACCESS_KEY), Layout = "${longdate}|[${level}]|${logger}|${message}${onexception:inner=|${exception}${when:when=(level > LogLevel.Warn):inner=|[!] ${exception:format=ToString:innerFormat=Message:maxInnerExceptionLevel=5} }}" }; //awsTarget.Layout = ""; config.AddTarget("aws", awsTarget); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, consoleTarget)); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, awsTarget)); LogManager.Configuration = config; target = LogManager.Configuration.FindTargetByName("aws"); exceptions = new List <Exception>(); }
public void ConfigNLogToUseAWSCloudWatch() { var config = new LoggingConfiguration(); //I would have preferred to have this configured on NLog.config //However, Region is required and I don't want to duplicated //Reason why it is implemented here - NO DUPLICATIONS!! lol var awsTarget = new AWSTarget() { LogGroup = "Paulo-Forro-GroupLogs", Region = _aWSRegionEndpoint }; config.AddTarget("aws", awsTarget); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, awsTarget)); //Write other logs destinations as well var logfile = new NLog.Targets.FileTarget("logfile") { FileName = "file.txt" }; var logconsole = new NLog.Targets.ConsoleTarget("logconsole"); config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole); config.AddRule(LogLevel.Info, LogLevel.Fatal, logfile); LogManager.Configuration = config; }
// //============================================================================= /// <summary> /// configure target "aws" for AWS CloudWatch /// </summary> /// <param name="core"></param> public static void awsConfigure(CoreController core) { if (core.serverConfig == null) { return; } if (string.IsNullOrWhiteSpace(core.serverConfig.awsCloudWatchLogGroup)) { return; } var awsTarget = new AWSTarget { Layout = "${longdate}|${level:uppercase=true}|${callsite}|${message}", LogGroup = core.serverConfig.awsCloudWatchLogGroup, Region = core.awsCredentials.awsRegion.DisplayName, Credentials = new Amazon.Runtime.BasicAWSCredentials(core.awsCredentials.awsAccessKeyId, core.awsCredentials.awsSecretAccessKey), LogStreamNamePrefix = core.appConfig.name, LogStreamNameSuffix = "NLog", MaxQueuedMessages = 5000 }; var config = new LoggingConfiguration(); config.AddTarget("aws", awsTarget); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, awsTarget)); LogManager.Configuration = config; }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { var config = new LoggingConfiguration(); var awsTarget = new AWSTarget() { LogGroup = "idkpopup-website", Region = "us-west-1" }; config.AddTarget("aws", awsTarget); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, awsTarget)); LogManager.Configuration = config; if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseRouting(); //Wire endpoings app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); endpoints.MapControllerRoute( "register", "api/register", new { controller = "Register", action = "Post" }); endpoints.MapControllerRoute( "register", "playbook/{action=playbook}", new { controller = "Playbook" }); }); logger.Info("Routes configured, starting up"); }
private static void Configure() { LoggingConfiguration config = new LoggingConfiguration(); var awsTarget = new AWSTarget() { LogGroup = "StreamingLive.Lambda", Region = "us-east-2" }; config.AddTarget("aws", awsTarget); config.LoggingRules.Add(new LoggingRule("*", logLevel, awsTarget)); LogManager.Configuration = config; configured = true; }
private void ConfigureNLog() { LogLevel logLevel = GetLogLevel(); var config = new LoggingConfiguration(); var awsTarget = new AWSTarget() { LogGroup = "/aws/lambda/APSKinesisLamdaFunction", Region = "us-east-1" }; config.AddTarget("aws", awsTarget); config.LoggingRules.Add(new LoggingRule("*", logLevel, awsTarget)); LogManager.Configuration = config; }
static void ConfigureNLog() { var config = new LoggingConfiguration(); var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); var awsTarget = new AWSTarget() { LogGroup = "NLog.ProgrammaticConfigurationExample", Region = "us-east-1" }; config.AddTarget("aws", awsTarget); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, consoleTarget)); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, awsTarget)); LogManager.Configuration = config; }
public static IServiceCollection InitDI(this IServiceCollection services, IConfiguration configuration) { services.ConfigureMRToken(configuration, "TokenOptions"); services.ConfigurateMRIdentity <User, RepositoryUser, ManagerUser>(configuration, "MongoDatabaseConnection", options => { options.Password.RequireDigit = false; options.Password.RequiredLength = 8; options.Password.RequireLowercase = false; options.Password.RequireNonAlphanumeric = false; options.SignIn.RequireConfirmedEmail = false; options.SignIn.RequireConfirmedPhoneNumber = false; options.Tokens.AuthenticatorTokenProvider = JwtBearerDefaults.AuthenticationScheme; }); services.Scan(scan => { scan .FromAssemblyOf <IRepositoryProvider>() .AddClasses() .AsSelf() .WithTransientLifetime() .FromAssemblyOf <RepositoryProvider>() .AddClasses() .AsImplementedInterfaces() .WithTransientLifetime() .FromAssemblyOf <Manager>() .AddClasses() .AsImplementedInterfaces() .WithTransientLifetime() .FromAssemblyOf <RepositoryRole>() .AddClasses() .AsSelf() .WithTransientLifetime(); }); // connectors var bucketImageDOptions = new BucketOptions(); configuration.Bind("DBucketOptions", bucketImageDOptions); services.AddTransient <ConnectorBucketImageD>(x => new ConnectorBucketImageD(Options.Create(bucketImageDOptions))); var bucketImageROptions = new BucketOptions(); configuration.Bind("RBucketOptions", bucketImageROptions); services.AddTransient <ConnectorBucketImageR>(x => new ConnectorBucketImageR(Options.Create(bucketImageROptions))); services.Configure <EmailServiceOptions>(options => configuration.GetSection("EmailService").Bind(options)); services.Configure <RabbitOptions>(options => configuration.GetSection("Rabbit").Bind(options)); services.AddTransient <ITemplateBuilder, TemplateBuilder>(); services.AddTransient <EmailSender>(); // loggers var awsLogOptions = new AwsLogOptions(); configuration.Bind("AwsLogOptions", awsLogOptions); var loggingConfig = new LoggingConfiguration(); var awsTarget = new AWSTarget { Name = "aws", LogGroup = awsLogOptions.TargetGroup, Region = awsLogOptions.Region, Credentials = new BasicAWSCredentials(awsLogOptions.AccessKey, awsLogOptions.SecretKey), Layout = "[${longdate}] (${callsite}) ${newline} ${aspnet-mvc-controller}/${aspnet-mvc-action}/${aspnet-request} ${newline} ${aspnet-user-identity} ${newline} ${level} : ${message} ${exception:format=tostring}" }; LogManager.Configuration.AddTarget(awsTarget); LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, awsTarget)); return(services); }
/// <summary> /// This will email super admins a notification of an exception. The exception details /// are logged to AWS CloudWatch. /// </summary> /// <param name="exception">The captured exception object.</param> /// <param name="emailText">The body text to send in the email.</param> public void handleError(Exception exception, string emailText) { //Send the Super Admins a notification try { //Let's not get stuck in a loop, if an excpeption occurs at the email code don't try to email if (emailText != "Exception occured attempting to send email.") { //Fire off email Email email = new Email(); //Add custom recipients here //email.SendEmail("*****@*****.**", WebConfigurationManager.AppSettings["loginTitle"].ToString() + " Exception", emailText); //email.SendEmail("*****@*****.**", WebConfigurationManager.AppSettings["loginTitle"].ToString() + " Exception", emailText); //Add Exception details to the email message text in the same format that is sent to AWS below //if stack trace is null reference then targetsite also returns null reference //Get the name of the method that threw the exception MethodBase site = exception.TargetSite; string methodName = site == null ? null : site.Name; //Get the filename and linenumber that threw the exception var st = new StackTrace(exception, true); var frame = st.GetFrame(0); var line = frame.GetFileLineNumber(); var filename = frame.GetFileName(); //Attach the full error message to the custom one sent in from the controller source //Current Format is: [FileName:value][MethodName:value][LineNumber:value][RawMessage:value] var full_error_message = "[Filename:" + filename + "][MethodName:" + methodName + "][LineNumber:" + line + "][RawMessage:" + exception.Message.ToString() + "]"; emailText += full_error_message; //Email Super Admins about the exception email.EmailSuperAdmins(WebConfigurationManager.AppSettings["loginTitle"].ToString() + " Exception", emailText); } } //Logging to the System Error log requires some configuration //1) Add a Registry(Folder) Key on the server/localhost. The last folder name matching the web config loginTitle key value // -> “HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\WRDSB\System.Web.Configuration.WebConfigurationManager.AppSettings["loginTitle"].ToString()” //2) Add a "String Value" titled "EventMessageFile" with a value of "C:\Windows\Microsoft.NET\Framework64\v4.0.30319\EventLogMessages.dll" //See Documentation for more detailed instructions: //https://staff.wrdsb.ca/software-development/documentation/dot-net-theme/general-configuration-options/ catch (Exception ex) { System.Diagnostics.EventLog log = new System.Diagnostics.EventLog(); string errorMessage = "Message: " + ex.Message + "\r\nSource: " + ex.Source + "\r\nStack: " + ex.StackTrace; if (ex.TargetSite != null) { errorMessage += "\r\nTarget: " + ex.TargetSite.ToString(); } if (ex.InnerException != null) { errorMessage += "\r\nInner: " + ex.InnerException.ToString(); } log.Source = WebConfigurationManager.AppSettings["loginTitle"].ToString(); log.WriteEntry(errorMessage, System.Diagnostics.EventLogEntryType.Error); } //You can now log the error to Azure or AWS or even both. //Send the exception information to AWS Cloudwatch //This requires configuration, see documentation: //https://staff.wrdsb.ca/software-development/documentation/dot-net-theme/general-configuration-options/ try { //Set the logging group based on debug/production switch //Logs will be sent to "/dotnet/$your_applictation_name/$environment #if DEBUG string environment = "test"; #else string environment = "production"; #endif //Set the AWS values, log group, log level var config = new LoggingConfiguration(); //The log group name cannot have spaces, but the loginTitle is meant to be human readable, transform it for format AWS requires var application_name = WebConfigurationManager.AppSettings["loginTitle"].ToString().ToLower().Replace(" ", "_"); var awsTarget = new AWSTarget() { LogGroup = "/dotnet/" + application_name + "/" + environment, Region = "us-east-1" }; config.AddTarget("aws", awsTarget); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Fatal, awsTarget)); LogManager.Configuration = config; Logger logger = LogManager.GetCurrentClassLogger(); //if stack trace is null reference then targetsite also returns null reference //Get the name of the method that threw the exception MethodBase site = exception.TargetSite; string methodName = site == null ? null : site.Name; //Get the filename and linenumber that threw the exception var st = new StackTrace(exception, true); var frame = st.GetFrame(0); var line = frame.GetFileLineNumber(); var filename = frame.GetFileName(); //Send the event to AWS CloudWatch //Current Format is: [FileName:value][MethodName:value][LineNumber:value][RawMessage:value] //This will be found in the Message portion of Cloudwatch logs logger.Fatal("[Filename:" + filename + "][MethodName:" + methodName + "][LineNumber:" + line + "][RawMessage:" + exception.Message.ToString() + "]"); } catch (Exception ex) { System.Diagnostics.EventLog log = new System.Diagnostics.EventLog(); string errorMessage = "Message: " + ex.Message + "\r\nSource: " + ex.Source + "\r\nStack: " + ex.StackTrace; if (ex.TargetSite != null) { errorMessage += "\r\nTarget: " + ex.TargetSite.ToString(); } if (ex.InnerException != null) { errorMessage += "\r\nInner: " + ex.InnerException.ToString(); } log.Source = WebConfigurationManager.AppSettings["loginTitle"].ToString(); log.WriteEntry(errorMessage, System.Diagnostics.EventLogEntryType.Error); } //Send the exception information to Azure Log Analytics //This requires configuration, see documentation: //https://staff.wrdsb.ca/software-development/documentation/dot-net-theme/general-configuration-options/ string result = string.Empty; try { string customer_id = WebConfigurationManager.AppSettings["workspace_id"].ToString(); string shared_key = WebConfigurationManager.AppSettings["primary_key"].ToString(); #if DEBUG string environment = "test"; #else string environment = "production"; #endif var application_name = WebConfigurationManager.AppSettings["loginTitle"].ToString().ToLower().Replace(" ", ""); string log_name = "dotnet" + application_name + environment; string timestamp = DateTime.Now.ToString(); //if stack trace is null reference then targetsite also returns null reference //Get the name of the method that threw the exception MethodBase site = exception.TargetSite; string methodName = site == null ? null : site.Name; //Get the filename and linenumber that threw the exception var st = new StackTrace(exception, true); var frame = st.GetFrame(0); var line = frame.GetFileLineNumber(); var filename = frame.GetFileName(); dynamic jsonObject = new JObject(); jsonObject.Add("FileName", filename); jsonObject.Add("MethodName", methodName); jsonObject.Add("LineNumber", line); jsonObject.Add("RawMessage", exception.Message.ToString()); string json = jsonObject.ToString(Newtonsoft.Json.Formatting.None); // Create a hash for the API signature var datestring = DateTime.UtcNow.ToString("r"); var jsonBytes = Encoding.UTF8.GetBytes(json); string stringToHash = "POST\n" + jsonBytes.Length + "\napplication/json\n" + "x-ms-date:" + datestring + "\n/api/logs"; string hashedString = BuildSignature(stringToHash, shared_key); string signature = "SharedKey " + customer_id + ":" + hashedString; string url = "https://" + customer_id + ".ods.opinsights.azure.com/api/logs?api-version=2016-04-01"; System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(); client.DefaultRequestHeaders.Add("Accept", "application/json"); client.DefaultRequestHeaders.Add("Log-Type", log_name); client.DefaultRequestHeaders.Add("Authorization", signature); client.DefaultRequestHeaders.Add("x-ms-date", datestring); client.DefaultRequestHeaders.Add("time-generated-field", timestamp); System.Net.Http.HttpContent httpContent = new StringContent(json, Encoding.UTF8); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); Task <System.Net.Http.HttpResponseMessage> response = client.PostAsync(new Uri(url), httpContent); System.Net.Http.HttpContent responseContent = response.Result.Content; result = responseContent.ReadAsStringAsync().Result; } catch (Exception ex) { System.Diagnostics.EventLog log = new System.Diagnostics.EventLog(); string errorMessage = "Message: " + ex.Message + "\r\nSource: " + ex.Source + "\r\nStack: " + ex.StackTrace; if (ex.TargetSite != null) { errorMessage += "\r\nTarget: " + ex.TargetSite.ToString(); } if (ex.InnerException != null) { errorMessage += "\r\nInner: " + ex.InnerException.ToString(); } if (!String.IsNullOrEmpty(result)) { errorMessage += "\r\nAzureResponse: " + result; } log.Source = WebConfigurationManager.AppSettings["loginTitle"].ToString(); log.WriteEntry(errorMessage, System.Diagnostics.EventLogEntryType.Error); } }