/// <summary> /// Shows how to retrieve an email from Microsoft exchange server using OpenEntityStream method /// </summary> public static void RetrieveEmailUsingOpenEntityStream() { //ExStart:RetrieveEmailUsingOpenEntityStream // Create connection info var info = EmailConnectionInfo.CreateEwsConnectionInfo(@"https://outlook.office365.com/ews/exchange.asmx", "username", "password"); // Create an email container using (var container = new EmailContainer(info)) { // Iterate over emails foreach (var entity in container.Entities) { // Create a stream with content of email var stream = container.OpenEntityStream(entity); // or var stream = entity.OpenStream(); // Create a text extractor for email using (var extractor = new EmailTextExtractor(stream)) { // Extract all the text from email Console.WriteLine(extractor.ExtractAll()); } } } //ExEnd:RetrieveEmailUsingOpenEntityStream }
/// <summary> /// Shows how to retrieve an email from IMAP server using OpenEntityStream method /// </summary> public static void RetrieveEmailUsingOpenEntityStreamIMAP() { //ExStart:RetrieveEmailUsingOpenEntityStream // Create connection info var info = EmailConnectionInfo.CreateImapConnectionInfo(@"imap-mail.outlook.com", 995, "username", "password"); // Create an email container using (var container = new EmailContainer(info)) { // Iterate over emails foreach (var entity in container.Entities) { // Create a stream with content of email var stream = container.OpenEntityStream(entity); // or var stream = entity.OpenStream(); // Create a text extractor for email using (var extractor = new EmailTextExtractor(stream)) { // Extract all the text from email Console.WriteLine(extractor.ExtractAll()); } } } //ExEnd:RetrieveEmailUsingOpenEntityStreamPOP3 }
public static EmailConnectionInfo GetEmailConnectionInfo(SmtpSection smtpSection, string subject, string fromEmail, string toEmail) { Contract.Requires(smtpSection != null); Contract.Requires(smtpSection.Network != null); Contract.Requires(string.IsNullOrWhiteSpace(subject) == false); Contract.Requires(string.IsNullOrWhiteSpace(toEmail) == false); Contract.Ensures(Contract.Result <EmailConnectionInfo>() != null); var info = new EmailConnectionInfo { Port = smtpSection.Network.Port, MailServer = smtpSection.Network.Host, FromEmail = fromEmail, EnableSsl = smtpSection.Network.EnableSsl, EmailSubject = subject, ToEmail = toEmail }; if (smtpSection.Network.DefaultCredentials == false) { info.NetworkCredentials = new NetworkCredential(smtpSection.Network.UserName, smtpSection.Network.Password); } return(info); }
/// <summary> /// Creates the logger for the application /// </summary> private static ILogger CreateLogger(IConfigurationRoot configuration) { var loggerConfig = new LoggerConfiguration() .MinimumLevel.Debug() .MinimumLevel.Override("Microsoft", LogEventLevel.Information) .MinimumLevel.Override("System", LogEventLevel.Information) .Enrich.FromLogContext() .WriteTo.Async(c => c.File( "../Logs/appLog_.txt", outputTemplate: GetLoggingTemplate(), rollingInterval: RollingInterval.Day )); ExceptionOptions errorSettings = configuration.GetSection("exceptions").Get <ExceptionOptions>(); if (String.IsNullOrEmpty(errorSettings.MailTo) == false) { EmailConnectionInfo emailInfo = new EmailConnectionInfo { EmailSubject = $"Seed Project: Unhandled Exception occurred on machine {Environment.MachineName}", MailServer = errorSettings.SmtpServer, FromEmail = errorSettings.MailFrom, ToEmail = errorSettings.MailTo }; loggerConfig.WriteTo.Email(emailInfo, GetLoggingTemplate(), LogEventLevel.Error); } #if DEBUG //we will only use the console logger when debugging loggerConfig.WriteTo.Console(outputTemplate: GetLoggingTemplate()); #endif return(loggerConfig.CreateLogger()); }
/// <summary> /// Adds a sink that sends log events via email. /// </summary> /// <param name="loggerConfiguration">The logger configuration.</param> /// <param name="fromEmail">The email address emails will be sent from</param> /// <param name="toEmails">The email addresses emails will be sent to</param> /// <param name="mailServer">The SMTP email server to use</param> /// <param name="networkCredential">The network credentials to use to authenticate with mailServer</param> /// <param name="outputTemplate">A message template describing the format used to write to the sink. /// the default is "{Timestamp} [{Level}] {Message}{NewLine}{Exception}".</param> /// <param name="restrictedToMinimumLevel">The minimum log event level required in order to write an event to the sink.</param> /// <param name="batchPostingLimit">The maximum number of events to post in a single batch.</param> /// <param name="period">The time to wait between checking for event batches.</param> /// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param> /// <returns>Logger configuration, allowing configuration to continue.</returns> /// <exception cref="ArgumentNullException">A required parameter is null.</exception> public static LoggerConfiguration Email( this LoggerSinkConfiguration loggerConfiguration, string fromEmail, IEnumerable <string> toEmails, string mailServer, ICredentialsByHost networkCredential = null, string outputTemplate = DefaultOutputTemplate, LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum, int batchPostingLimit = EmailSink.DefaultBatchPostingLimit, TimeSpan?period = null, IFormatProvider formatProvider = null) { if (loggerConfiguration == null) { throw new ArgumentNullException("loggerConfiguration"); } if (fromEmail == null) { throw new ArgumentNullException("fromEmail"); } if (toEmails == null) { throw new ArgumentNullException("toEmails"); } var connectionInfo = new EmailConnectionInfo { FromEmail = fromEmail, ToEmail = string.Join(";", toEmails), MailServer = mailServer, NetworkCredentials = networkCredential }; return(Email(loggerConfiguration, connectionInfo, outputTemplate, restrictedToMinimumLevel, batchPostingLimit, period, formatProvider)); }
internal static LoggerConfiguration Email(this LoggerSinkConfiguration loggerSinkConfiguration, MailConfig mailConfig) { port = mailConfig.Port; enableSsl = mailConfig.EnableSsl; toEmails = mailConfig.ToEmails; server = mailConfig.Server; networkCredentials = mailConfig.NetworkCredentials; var emailInfo = new EmailConnectionInfo { FromEmail = networkCredentials.UserName, ToEmail = string.Join(';', toEmails), MailServer = server, EmailSubject = subject, EnableSsl = enableSsl, Port = port }; if (!string.IsNullOrEmpty(networkCredentials.Password)) { emailInfo.NetworkCredentials = networkCredentials; } AddSerilogEmailFailsafe(); return(loggerSinkConfiguration.Email(emailInfo, restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Error)); }
public Startup(IConfiguration configuration) { Configuration = configuration; // Configuring Serilog. TODO -> Find better place for this than a constructor. var serilogOptions = new SerilogOptions(); Configuration.Bind("SerilogOptions", serilogOptions); var networkCredential = new NetworkCredential( serilogOptions.FromEmail, serilogOptions.FromEmailPassword); var emailConnectionInfo = new EmailConnectionInfo { Port = serilogOptions.Port, FromEmail = serilogOptions.FromEmail, ToEmail = serilogOptions.ToEmail, EnableSsl = serilogOptions.EnableSsl, EmailSubject = serilogOptions.EmailSubject, MailServer = serilogOptions.SmtpServer, NetworkCredentials = networkCredential }; Log.Logger = new LoggerConfiguration() .MinimumLevel.Information() .WriteTo.Console() .WriteTo.Email(emailConnectionInfo, restrictedToMinimumLevel: LogEventLevel.Error) .CreateLogger(); }
/// <summary> /// Adds a sink that sends log events via email. /// </summary> /// <param name="loggerConfiguration">The logger configuration.</param> /// <param name="connectionInfo">The connection info used for</param> /// <param name="textFormatter">ITextFormatter implementation to write log entry to email.</param> /// <param name="restrictedToMinimumLevel">The minimum log event level required in order to write an event to the sink.</param> /// <param name="batchPostingLimit">The maximum number of events to post in a single batch.</param> /// <param name="period">The time to wait between checking for event batches.</param> /// <param name="mailSubject">The subject, can be a plain string or a template such as {Timestamp} [{Level}] occurred.</param> /// <returns> /// Logger configuration, allowing configuration to continue. /// </returns> /// <exception cref="ArgumentNullException">A required parameter is null.</exception> /// <exception cref="System.ArgumentNullException">connectionInfo /// or /// textFormatter</exception> public static LoggerConfiguration Email( this LoggerSinkConfiguration loggerConfiguration, EmailConnectionInfo connectionInfo, ITextFormatter textFormatter, LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum, int batchPostingLimit = DefaultBatchPostingLimit, TimeSpan?period = null, string mailSubject = EmailConnectionInfo.DefaultSubject) { if (connectionInfo == null) { throw new ArgumentNullException("connectionInfo"); } if (textFormatter == null) { throw new ArgumentNullException("textFormatter"); } ITextFormatter mailSubjectFormatter = new MessageTemplateTextFormatter(mailSubject, null); var batchingPeriod = period ?? DefaultPeriod; var batchingOptions = new PeriodicBatchingSinkOptions { BatchSizeLimit = batchPostingLimit, Period = batchingPeriod, EagerlyEmitFirstEvent = false, // set default to false, not usable for emailing QueueLimit = 10000 }; var batchingSink = new PeriodicBatchingSink(new EmailSink(connectionInfo, textFormatter, mailSubjectFormatter), batchingOptions); return(loggerConfiguration.Sink(batchingSink, restrictedToMinimumLevel)); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { #region Serilog configuration LoggerConfiguration serilogConfiguration = new LoggerConfiguration(); SerilogEmailParamsDto serilogParams = Configuration.GetSection("SerilogEmailParams").Get <SerilogEmailParamsDto>(); serilogParams.Destinations.ForEach(destination => { EmailConnectionInfo emailConnectionInfo = new EmailConnectionInfo { EmailSubject = serilogParams.Subject, FromEmail = serilogParams.FromEmail, SendGridClient = new SendGridClient(serilogParams.ApiKeySendGrid), FromName = serilogParams.FromName, ToEmail = destination }; serilogConfiguration.ReadFrom.Configuration(Configuration) .WriteTo.Email(emailConnectionInfo, restrictedToMinimumLevel: serilogParams.LogEventLevel, period: TimeSpan.FromMinutes(5)); }); Log.Logger = serilogConfiguration.CreateLogger(); services.AddLogging(configure => { configure.AddSerilog(); }); #endregion services.AddControllersWithViews(); }
/// <summary> /// Adds a sink that sends log events via email. /// </summary> /// <param name="loggerConfiguration">The logger configuration.</param> /// <param name="connectionInfo">The connection info used for </param> /// <param name="restrictedToMinimumLevel">The minimum log event level required in order to write an event to the sink.</param> /// <param name="batchPostingLimit">The maximum number of events to post in a single batch.</param> /// <param name="period">The time to wait between checking for event batches.</param> /// <param name="textFormatter">ITextFormatter implementation to write log entry to email.</param> /// <param name="mailSubject">The subject, can be a plain string or a template such as {Timestamp} [{Level}] occurred.</param> /// <returns>Logger configuration, allowing configuration to continue.</returns> /// <exception cref="ArgumentNullException">A required parameter is null.</exception> public static LoggerConfiguration Email( this LoggerSinkConfiguration loggerConfiguration, EmailConnectionInfo connectionInfo, ITextFormatter textFormatter, LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum, int batchPostingLimit = EmailSink.DefaultBatchPostingLimit, TimeSpan?period = null, string mailSubject = EmailConnectionInfo.DefaultSubject) { if (connectionInfo == null) { throw new ArgumentNullException("connectionInfo"); } if (textFormatter == null) { throw new ArgumentNullException("textFormatter"); } ITextFormatter mailSubjectFormatter = new MessageTemplateTextFormatter(mailSubject, null); var defaultedPeriod = period ?? EmailSink.DefaultPeriod; return(loggerConfiguration.Sink( new EmailSink(connectionInfo, batchPostingLimit, defaultedPeriod, textFormatter, mailSubjectFormatter), restrictedToMinimumLevel)); }
/// <summary> /// Adds a sink that sends log events via email. /// </summary> /// <param name="loggerConfiguration">The logger configuration.</param> /// <param name="connectionInfo">The connection info used for </param> /// <param name="outputTemplate">A message template describing the format used to write to the sink. /// the default is "{Timestamp} [{Level}] {Message}{NewLine}{Exception}".</param> /// <param name="restrictedToMinimumLevel">The minimum log event level required in order to write an event to the sink.</param> /// <param name="batchPostingLimit">The maximum number of events to post in a single batch.</param> /// <param name="period">The time to wait between checking for event batches.</param> /// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param> /// <param name="mailSubject">The subject, can be a plain string or a template such as {Timestamp} [{Level}] occurred.</param> /// <returns>Logger configuration, allowing configuration to continue.</returns> /// <exception cref="ArgumentNullException">A required parameter is null.</exception> public static LoggerConfiguration Email( this LoggerSinkConfiguration loggerConfiguration, EmailConnectionInfo connectionInfo, string outputTemplate = DefaultOutputTemplate, LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum, int batchPostingLimit = EmailSink.DefaultBatchPostingLimit, TimeSpan?period = null, IFormatProvider formatProvider = null, string mailSubject = EmailConnectionInfo.DefaultSubject) { if (connectionInfo == null) { throw new ArgumentNullException("connectionInfo"); } if (!string.IsNullOrEmpty(connectionInfo.EmailSubject)) { mailSubject = connectionInfo.EmailSubject; } var defaultedPeriod = period ?? EmailSink.DefaultPeriod; var formatter = new MessageTemplateTextFormatter(outputTemplate, formatProvider); var subjectLineFormatter = new MessageTemplateTextFormatter(mailSubject, formatProvider); return(loggerConfiguration.Sink( new EmailSink(connectionInfo, batchPostingLimit, defaultedPeriod, formatter, subjectLineFormatter), restrictedToMinimumLevel)); }
public static Logger 多种输出方式配置() { var emailInfo = new EmailConnectionInfo { EmailSubject = "Serilog Email Learning", EnableSsl = false, FromEmail = "*****@*****.**", MailServer = "smtp.qq.com", ToEmail = "*****@*****.**", NetworkCredentials = new NetworkCredential("*****@*****.**", "hkmkqwrtvxtgfiac")//在邮箱的SMTP服务 生成授权码 }; var logger = new LoggerConfiguration() .WriteTo.Console() .WriteTo.File("Learning.txt") .WriteTo.Email(emailInfo) .WriteTo.File("Learning-.txt", rollingInterval: RollingInterval.Day) .CreateLogger(); logger.Information("Nothing"); //需要调用Dispose来发送邮件 //其实想想也算合理,不可能每有一条日志就发一次邮件,等到日志写好了再一次性发送 logger.Dispose(); return(logger); }
/// <summary> /// Adds a sink that sends log events via email. /// </summary> /// <param name="loggerConfiguration">The logger configuration.</param> /// <param name="fromEmail">The email address emails will be sent from</param> /// <param name="toEmail">The email address emails will be sent to</param> /// <param name="outputTemplate">A message template describing the format used to write to the sink. /// the default is "{Timestamp} [{Level}] {Message}{NewLine}{Exception}".</param> /// <param name="restrictedToMinimumLevel">The minimum log event level required in order to write an event to the sink.</param> /// <param name="batchPostingLimit">The maximum number of events to post in a single batch.</param> /// <param name="period">The time to wait between checking for event batches.</param> /// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param> /// <param name="mailSubject">The subject, can be a plain string or a template such as {Timestamp} [{Level}] occurred.</param> /// <returns> /// Logger configuration, allowing configuration to continue. /// </returns> /// <exception cref="ArgumentNullException">A required parameter is null.</exception> /// <exception cref="System.ArgumentNullException">loggerConfiguration /// or /// fromEmail /// or /// toEmail</exception> public static LoggerConfiguration Email( this LoggerSinkConfiguration loggerConfiguration, string fromEmail, string toEmail, string outputTemplate = DefaultOutputTemplate, LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum, int batchPostingLimit = DefaultBatchPostingLimit, TimeSpan?period = null, IFormatProvider formatProvider = null, string mailSubject = EmailConnectionInfo.DefaultSubject) { if (loggerConfiguration == null) { throw new ArgumentNullException("loggerConfiguration"); } if (fromEmail == null) { throw new ArgumentNullException("fromEmail"); } if (toEmail == null) { throw new ArgumentNullException("toEmail"); } var connectionInfo = new EmailConnectionInfo { FromEmail = fromEmail, ToEmail = toEmail, EmailSubject = mailSubject }; return(Email(loggerConfiguration, connectionInfo, outputTemplate, restrictedToMinimumLevel, batchPostingLimit, period, formatProvider)); }
public SerilogEmailModule(EmailConnectionInfo emailConnectionInfo, LogEventLevel defaultMinimumLevel) { Contract.Requires(emailConnectionInfo != null); _emailConnectionInfo = emailConnectionInfo; _defaultMinimumLevel = defaultMinimumLevel; }
protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines) { base.ApplicationStartup(container, pipelines); StaticConfiguration.DisableErrorTraces = false; pipelines.AfterRequest += ctx => { ctx.Response.Headers.Add("Access-Control-Allow-Origin", "*"); ctx.Response.Headers.Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); ctx.Response.Headers.Add("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE"); }; var email = new EmailConnectionInfo { EmailSubject = "DAQ Log Email", FromEmail = "*****@*****.**", ToEmail = "*****@*****.**", MailServer = "send.state.ut.us", Port = 25 }; var dir = Path.Combine(HttpRuntime.AppDomainAppPath, @"logs\daq.log-{Date}.txt"); var levelSwitch = new LoggingLevelSwitch(); Log.Logger = new LoggerConfiguration() .MinimumLevel.ControlledBy(levelSwitch) .WriteTo.RollingFile(dir) .WriteTo.Email(email, restrictedToMinimumLevel: LogEventLevel.Error) .CreateLogger(); container.Register <ArcOnlineHttpClient>().AsSingleton(); container.Register <IArcOnlineCredentials, AgoCredentials>().AsSingleton(); #if DEBUG levelSwitch.MinimumLevel = LogEventLevel.Verbose; container.Register <IShareMappable, DocumentumMockShare>().AsSingleton(); container.Register <IRepository, EdocsMockRepository>().AsPerRequestSingleton(); #elif STAGING levelSwitch.MinimumLevel = LogEventLevel.Debug; container.Register <IShareMappable, DocumentumShare>().AsSingleton(); container.Register <IRepository, EdocsRepository>().AsPerRequestSingleton(); #else levelSwitch.MinimumLevel = LogEventLevel.Debug; container.Register <IShareMappable, DocumentumShare>().AsSingleton(); container.Register <IRepository, EdocsRepository>().AsPerRequestSingleton(); StaticConfiguration.DisableErrorTraces = true; #endif Log.Debug("Logging initialized"); var folder = container.Resolve <IShareMappable>(); var driveLetter = ConfigurationManager.AppSettings["share_drive_letter"]; folder.CreateMap(driveLetter); }
public Startup(IConfiguration configuration) { Configuration = configuration; Serilog.Debugging.SelfLog.Enable(Console.WriteLine); /* * var builder = new ConfigurationBuilder() * .SetBasePath(env.ContentRootPath) * .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) * .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true); * * if (env.IsDevelopment()) * { * // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709 * //builder.AddUserSecrets(); * } * * * builder.AddEnvironmentVariables(); * Configuration = builder.Build(); */ EmailConnectionInfo info = new EmailConnectionInfo() { EmailSubject = "Test Serilog", ToEmail = "*****@*****.**", FromEmail = "*****@*****.**", MailServer = "smtp.gmail.com", // "smtp.live.com" NetworkCredentials = new NetworkCredential("*****@*****.**", "acts15:23GOOG"), Port = 587, /* * FromEmail = "*****@*****.**", * MailServer = "smtp.live.com", // "smtp.live.com" * NetworkCredentials = new NetworkCredential("*****@*****.**", "acts15:23hot"), * Port = 465, // 465 */ }; // Or This: See https://github.com/serilog/serilog/wiki/Getting-Started var uriMongoDB = Configuration.GetValue <string>("MongoSettings:mongoconnection"); // http://sourcebrowser.io/Browse/serilog/serilog/src/Serilog.Sinks.Email/LoggerConfigurationEmailExtensions.cs Log.Logger = new LoggerConfiguration() .MinimumLevel.Warning() .ReadFrom.Configuration(Configuration) .WriteTo.Console() //.WriteTo.LiterateConsole() //.WriteTo.RollingFile("logs\\trackmed-{Date}.txt") // .WriteTo.Email(info, restrictedToMinimumLevel: LogEventLevel.Warning) // https://github.com/serilog/serilog/wiki/Configuration-Basics#overriding-per-sink //.WriteTo.Seq("http://localhost:5341/") .WriteTo.MongoDBCapped(uriMongoDB, collectionName: "logsTrackMED") // https://github.com/serilog/serilog-sinks-mongodb .CreateLogger(); Log.Warning("TrackMED_Core21_MVC is launched"); }
public static int Main(string[] args) { //known issue with net core 2.2 related to in-process hosting //https://github.com/aspnet/AspNetCore.Docs/blob/master/aspnetcore/host-and-deploy/aspnet-core-module/samples_snapshot/2.x/CurrentDirectoryHelpers.cs CurrentDirectoryHelpers.SetCurrentDirectory(); var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json") .AddEnvironmentVariables() .Build(); var loggerConfig = new LoggerConfiguration() .ReadFrom.Configuration(configuration); var smtpConfig = configuration.GetSection("SMTP"); if (smtpConfig.GetChildren().Any()) { var emailConnectionInfo = new EmailConnectionInfo { FromEmail = smtpConfig["FromEmail"], ToEmail = smtpConfig["ToEmail"], MailServer = smtpConfig["MailServer"], NetworkCredentials = new NetworkCredential(smtpConfig["UserName"], smtpConfig["Password"]), Port = 587, EnableSsl = false, EmailSubject = smtpConfig["EmailSubject"] }; loggerConfig.WriteTo.Email(emailConnectionInfo, "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{Exception}{NewLine}", LogEventLevel.Error); } Log.Logger = loggerConfig.CreateLogger(); try { Log.Information("Starting web host"); CreateWebHostBuilder(args).Build().Run(); return(0); } catch (Exception ex) { Log.Fatal(ex, "Web Host terminated unexpectedly"); return(1); } finally { Log.CloseAndFlush(); } }
private bool valideEmailConnectionIfo(EmailConnectionInfo eci, NetworkCredential nc) { if (string.IsNullOrEmpty(eci.ToEmail)) { return(false); } else { string[] listedestinataires = eci.ToEmail.Split(","); foreach (var adresse in listedestinataires) { if (!ValideEmailAdresse(adresse)) { Debug.Assert(false, "Adresse destinataire invalide"); return(false); } } } if (string.IsNullOrEmpty(eci.MailServer)) { return(false); } if (string.IsNullOrEmpty(eci.FromEmail)) { return(false); } else { if (!ValideEmailAdresse(eci.FromEmail)) { if (!ValideEmailAdresse(eci.FromEmail)) { Debug.Assert(false, "Adresse expéditeur invalide"); return(false); } } } if (string.IsNullOrEmpty(nc.UserName)) { return(false); } if (string.IsNullOrEmpty(nc.Password)) { return(false); } if (eci.Port == 0) { return(false); } return(true); }
public static void Main(string[] args) { var connectionString = new ConfigurationBuilder().AddJsonFile("appsettings.json", false) .Build() .GetConnectionString("DefaultConnection"); const string logFilePath = "Logs.txt"; const string tableName = "Logs"; var columnOption = new ColumnOptions(); var emailInfo = new EmailConnectionInfo { FromEmail = "*****@*****.**", ToEmail = "*****@*****.**", MailServer = "smtp.gmail.com", EmailSubject = "An Log Error Occured in Tenant Pro Project, Please check it", Port = 465, EnableSsl = true, NetworkCredentials = new NetworkCredential("Enter your email here", "enter mail password") }; Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .Enrich.FromLogContext() .WriteTo.MSSqlServer(connectionString, tableName, columnOptions: columnOption, autoCreateSqlTable: true) .WriteTo.Email(emailInfo, outputTemplate: "Time : {Timestamp:HH:mm:ss}\t\n{Level:u3}\t\n" + "{SourceContext}\t\n{Message}{NewLine}{Exception}", LogEventLevel.Fatal, 1) .WriteTo.File(logFilePath, LogEventLevel.Error) .CreateLogger(); try { Log.Information("Application Starting up"); CreateHostBuilder(args).Build().Run(); } catch (Exception ex) { Log.Fatal(ex, "Application start-up failed"); } finally { Log.CloseAndFlush(); } }
public static void Main(string[] args) { var connectionString = new ConfigurationBuilder().AddJsonFile("appsettings.json", false) .Build() .GetConnectionString("DefaultConnection"); const string logFilePath = "Logs.txt"; var columnOptions = new ColumnOptions(); var emailInfo = new EmailConnectionInfo { FromEmail = "*****@*****.**", ToEmail = "*****@*****.**", MailServer = "smtp.gmail.com", EmailSubject = "An Log Error Occured in MonsterAir Project, Please check it", Port = 465, EnableSsl = true, NetworkCredentials = new NetworkCredential("*****@*****.**", "@1110597219@") }; Log.Logger = new LoggerConfiguration() .Enrich.FromLogContext() .WriteTo.MSSqlServer(connectionString, sinkOptions: new MSSqlServerSinkOptions { TableName = "Logs" } , null, null, LogEventLevel.Warning, null, columnOptions: columnOptions, null, null) .WriteTo.Email(emailInfo, outputTemplate: "Time : {Timestamp:HH:mm:ss}\t\n{Level:u3}\t\n" + "{SourceContext}\t\n{Message}{NewLine}{Exception}", LogEventLevel.Fatal, 1) .WriteTo.File(logFilePath, restrictedToMinimumLevel: LogEventLevel.Warning) .CreateLogger(); try { Log.Information("Application Starting up"); CreateHostBuilder(args).Build().Run(); } catch (Exception ex) { Log.Fatal(ex, "Application start-up failed"); } finally { Log.CloseAndFlush(); } }
public static void Register(string name) { var config = new GoogleCloudLoggingSinkOptions { UseJsonOutput = true, LogName = "api.mapserv.utah.gov", UseSourceContextAsLogName = false, ResourceType = "global", ServiceName = "api.mapserv.utah.gov", ServiceVersion = "1.12.5.5" }; #if DEBUG var projectId = "ut-dts-agrc-web-api-dv"; var fileName = "ut-dts-agrc-web-api-dv-log-writer.json"; var serviceAccount = File.ReadAllText(Path.Combine(HttpRuntime.AppDomainAppPath, fileName)); config.GoogleCredentialJson = serviceAccount; #else var projectId = "ut-dts-agrc-web-api-prod"; #endif config.ProjectId = projectId; var email = new EmailConnectionInfo { EmailSubject = "Geocoding Log Email", FromEmail = "*****@*****.**", ToEmail = "*****@*****.**" }; var levelSwitch = new LoggingLevelSwitch(); Log.Logger = new LoggerConfiguration() .MinimumLevel.ControlledBy(levelSwitch) .WriteTo.Email(email, restrictedToMinimumLevel: LogEventLevel.Error) .WriteTo.GoogleCloudLogging(config) .CreateLogger(); #if DEBUG levelSwitch.MinimumLevel = LogEventLevel.Verbose; #else levelSwitch.MinimumLevel = LogEventLevel.Information; #endif Log.Debug("Logging initialized"); }
private void SetupLogging() { var addinFolder = GetAddinFolder(); var logLocation = Path.Combine(addinFolder, "{Date}-log.txt"); var email = new EmailConnectionInfo { EmailSubject = "UIC Addin", FromEmail = "*****@*****.**", ToEmail = "*****@*****.**", MailServer = "send.state.ut.us", Port = 25 }; Log.Logger = new LoggerConfiguration() .WriteTo.Email(email, restrictedToMinimumLevel: LogEventLevel.Error) .WriteTo.RollingFile(logLocation, retainedFileCountLimit: 7) .MinimumLevel.Verbose() .CreateLogger(); }
public static LoggerConfiguration Email( this LoggerSinkConfiguration loggerConfiguration, string fromEmail, string toEmail, string mailServer, string mailUserName, string mailPassword, bool enableSsl = false, int port = 25, string mailSubject = EmailConnectionInfo.DefaultSubject, LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum) { if (loggerConfiguration == null) { throw new ArgumentNullException(nameof(loggerConfiguration)); } if (fromEmail == null) { throw new ArgumentNullException(nameof(fromEmail)); } if (toEmail == null) { throw new ArgumentNullException(nameof(toEmail)); } var connectionInfo = new EmailConnectionInfo { FromEmail = fromEmail, ToEmail = toEmail, MailServer = mailServer, Port = port, NetworkCredentials = new NetworkCredential(mailUserName, mailPassword), EmailSubject = mailSubject, EnableSsl = enableSsl, ServerCertificateValidationCallback = (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => { return(true); } }; return(loggerConfiguration.Email(connectionInfo, restrictedToMinimumLevel: restrictedToMinimumLevel)); }
/// <summary> /// Shows how to retrieve emails from Microsoft exchange server using Entity property /// </summary> public static void RetrieveEmailsUsingEntity() { //ExStart:RetrieveEmailsUsingEntity // Create connection info var info = EmailConnectionInfo.CreateEwsConnectionInfo(@"https://outlook.office365.com/ews/exchange.asmx", "username", "password"); // Create an email container using (var container = new EmailContainer(info)) { // Iterate over emails foreach (var entity in container.Entities) { Console.WriteLine("Folder: " + entity.Path.ToString()); // A folder at server Console.WriteLine("Subject: " + entity[MetadataNames.Subject]); // A subject of email Console.WriteLine("From: " + entity[MetadataNames.EmailFrom]); // "From" address Console.WriteLine("To: " + entity[MetadataNames.EmailTo]); // "To" addresses } } //ExEnd:RetrieveEmailsUsingEntity }
/// <summary> /// Shows how to retrieve emails from IMAP server using Entity property /// </summary> public static void RetrieveEmailsUsingEntityIMAP() { //ExStart:RetrieveEmailsUsingEntity // Create connection info var info = EmailConnectionInfo.CreateImapConnectionInfo(@"imap-mail.outlook.com", 995, "username", "password"); // Create an email container using (var container = new EmailContainer(info)) { // Iterate over emails foreach (var entity in container.Entities) { Console.WriteLine("Folder: " + entity.Path.ToString()); // A folder at server Console.WriteLine("Subject: " + entity[MetadataNames.Subject]); // A subject of email Console.WriteLine("From: " + entity[MetadataNames.EmailFrom]); // "From" address Console.WriteLine("To: " + entity[MetadataNames.EmailTo]); // "To" addresses Console.WriteLine("Date: " + entity.Date); Console.WriteLine("Size: " + entity.Size); } } //ExEnd:RetrieveEmailsUsingEntity }
private void ProcessEmailSection(IConfiguration conf, int cle, bool AlerteUniquement) { EmailConnectionInfo eci = null; NetworkCredential nc = null; nc = new NetworkCredential() { Password = conf.GetSection(string.Format("Serilog:WriteTo:{0}:Args:NetworkCredentials:Password", cle)).Value, UserName = conf.GetSection(string.Format("Serilog:WriteTo:{0}:Args:NetworkCredentials:UserName", cle)).Value, }; bool EnableSsl = false; bool IsBodyHtml = false; int Port = 0; bool result = bool.TryParse(conf.GetSection(string.Format("Serilog:WriteTo:{0}:Args:connectionInfo:EnableSsl", cle)).Value, out EnableSsl); result = bool.TryParse(conf.GetSection(string.Format("Serilog:WriteTo:{0}:Args:connectionInfo:IsBodyHtml", cle)).Value, out IsBodyHtml); result = int.TryParse(conf.GetSection(string.Format("Serilog:WriteTo:{0}:Args:connectionInfo:Port", cle)).Value, out Port); eci = new EmailConnectionInfo() { EmailSubject = conf.GetSection(string.Format("Serilog:WriteTo:{0}:Args:connectionInfo:EmailSubject", cle)).Value, FromEmail = conf.GetSection(string.Format("Serilog:WriteTo:{0}:Args:connectionInfo:FromEmail", cle)).Value, EnableSsl = EnableSsl, IsBodyHtml = IsBodyHtml, MailServer = conf.GetSection(string.Format("Serilog:WriteTo:{0}:Args:connectionInfo:MailServer", cle)).Value, Port = Port, ToEmail = conf.GetSection(string.Format("Serilog:WriteTo:{0}:Args:connectionInfo:ToEmail", cle)).Value, NetworkCredentials = nc, }; if (valideEmailConnectionIfo(eci, nc)) { //Construit loggerEmail ILogger emailLogger = new LoggerConfiguration() .MinimumLevel.Information() .WriteTo.Email(eci) .CreateLogger(); if (!AlerteUniquement) { if (!monDico.TryAdd(new Tuple <string, string>("Email", "Perf"), emailLogger)) { Debug.Assert(false, "Section Email en double!!!!"); } if (!monDico.TryAdd(new Tuple <string, string>("Email", "Diag"), emailLogger)) { Debug.Assert(false, "Section Email en double!!!!"); } if (!monDico.TryAdd(new Tuple <string, string>("Email", "Error"), emailLogger)) { Debug.Assert(false, "Section Email en double!!!!"); } if (!monDico.TryAdd(new Tuple <string, string>("Email", "Usage"), emailLogger)) { Debug.Assert(false, "Section Email en double!!!!"); } } else { if (!monDico.TryAdd(new Tuple <string, string>("Email", "Alerte"), emailLogger)) { Debug.Assert(false, "Alerte emailLogger Deja ajouté"); } } } }
private Serilog.ILogger CreatePipelineLogger(ILogPipelineProvider extraPipelineProvider = null) { var logSettings = extraPipelineProvider == null ? GlobalLogSettings : _extraPipelinesLogSettings[extraPipelineProvider]; var pipelineSwitchKey = GetLogLevelSwitchKey(extraPipelineProvider); var pipelineLevelSwitch = _pipelineLevelSwitches[pipelineSwitchKey]; var pipelineConfiguration = new LoggerConfiguration() .MinimumLevel.ControlledBy(pipelineLevelSwitch) .Enrich.FromLogContext() .Enrich.WithEnvironmentVariables(EnvironmentVariablesToLog) .Enrich.WithRebusCorrelationId(TransactionIdLogPropertyName) .Enrich.FromMassTransit();; const string extraPipelineFilter = "IsExtraLogPipeline = true"; if (extraPipelineProvider != null) { var pipelineProviderTypeName = extraPipelineProvider.GetType().Name; pipelineConfiguration .Filter.ByIncludingOnly($"{extraPipelineFilter} and {pipelineProviderTypeName}.Id = '{extraPipelineProvider.Id}'"); } else { pipelineConfiguration .Filter.ByExcluding(extraPipelineFilter); } if (logSettings.MongoDb.IsEnabled) { const LogSinkType sinkType = LogSinkType.MongoDb; var switchKey = GetLogLevelSwitchKey(sinkType, extraPipelineProvider); var levelSwitch = _pipelineLevelSwitches[switchKey]; pipelineConfiguration .WriteTo.Logger(mongoDbLogConfiguration => { mongoDbLogConfiguration .MinimumLevel.ControlledBy(levelSwitch) .Enrich.FromLogContext() .Enrich.WithEnvironmentVariables(EnvironmentVariablesToLog) .Enrich.WithRebusCorrelationId(TransactionIdLogPropertyName) .Enrich.FromMassTransit(); mongoDbLogConfiguration .WriteTo.MongoDBCapped(logSettings.MongoDb.ConnectionString, cappedMaxSizeMb: 512L, collectionName: logSettings.MongoDb.CollectionName, formatProvider: GetFormatProvider(logSettings.MongoDb.Culture ?? logSettings.Culture)); }); } if (logSettings.Slack.IsEnabled) { const LogSinkType sinkType = LogSinkType.Slack; var settings = logSettings.Slack; var switchKey = GetLogLevelSwitchKey(sinkType, extraPipelineProvider); var levelSwitch = _pipelineLevelSwitches[switchKey]; var slackOptions = new SlackSinkOptions { WebHookUrl = settings.WebHookUrl, CustomChannel = settings.CustomChannel, CustomUserName = settings.CustomUsername, CustomIcon = settings.CustomIcon, BatchSizeLimit = settings.BatchSizeLimit, Period = settings.Period }; pipelineConfiguration .WriteTo.Logger(slackLogConfiguration => { slackLogConfiguration .MinimumLevel.ControlledBy(levelSwitch) .Enrich.FromLogContext() .Enrich.WithEnvironmentVariables(EnvironmentVariablesToLog) .Enrich.WithRebusCorrelationId(TransactionIdLogPropertyName) .Enrich.FromMassTransit(); slackLogConfiguration .WriteTo.Slack(slackOptions, formatProvider: GetFormatProvider(logSettings.Slack.Culture ?? logSettings.Culture)); }); } if (logSettings.Email.IsEnabled) { const LogSinkType sinkType = LogSinkType.Email; var settings = logSettings.Email; var switchKey = GetLogLevelSwitchKey(sinkType, extraPipelineProvider); var levelSwitch = _pipelineLevelSwitches[switchKey]; var emailOptions = new EmailConnectionInfo { EmailSubject = settings.Subject, EnableSsl = settings.EnableSsl, FromEmail = settings.From, IsBodyHtml = settings.IsBodyHtml, MailServer = settings.SmtpHost, ToEmail = string.Join(";", settings.ToList) }; emailOptions.Port = settings.SmtpPort ?? emailOptions.Port; if (!string.IsNullOrWhiteSpace(settings.SmtpUser)) { emailOptions.NetworkCredentials = new NetworkCredential(settings.SmtpUser, settings.SmtpPass); } pipelineConfiguration .WriteTo.Logger(emailLogConfiguration => { emailLogConfiguration .MinimumLevel.ControlledBy(levelSwitch) .Enrich.FromLogContext() .Enrich.WithEnvironmentVariables(EnvironmentVariablesToLog) .Enrich.WithRebusCorrelationId(TransactionIdLogPropertyName) .Enrich.FromMassTransit(); emailLogConfiguration .WriteTo.Email(emailOptions, mailSubject: settings.Subject, formatProvider: GetFormatProvider(logSettings.Email.Culture ?? logSettings.Culture)); }); } if (logSettings.Seq.IsEnabled) { const LogSinkType sinkType = LogSinkType.Seq; var settings = logSettings.Seq; var switchKey = GetLogLevelSwitchKey(sinkType, extraPipelineProvider); var levelSwitch = _pipelineLevelSwitches[switchKey]; pipelineConfiguration .WriteTo.Logger(seqLogConfiguration => { seqLogConfiguration .MinimumLevel.ControlledBy(levelSwitch) .Enrich.FromLogContext() .Enrich.WithEnvironmentVariables(EnvironmentVariablesToLog) .Enrich.WithRebusCorrelationId(TransactionIdLogPropertyName) .Enrich.FromMassTransit(); seqLogConfiguration .WriteTo.Seq(settings.Host, apiKey: settings.ApiKey); }); } if (logSettings.ElasticSearch.IsEnabled) { const LogSinkType sinkType = LogSinkType.ElasticSearch; var settings = logSettings.ElasticSearch; var switchKey = GetLogLevelSwitchKey(sinkType, extraPipelineProvider); var levelSwitch = _pipelineLevelSwitches[switchKey]; pipelineConfiguration .WriteTo.Logger(elasticSearchLogConfiguration => { elasticSearchLogConfiguration .MinimumLevel.ControlledBy(levelSwitch) .Enrich.FromLogContext() .Enrich.WithEnvironmentVariables(EnvironmentVariablesToLog) .Enrich.WithRebusCorrelationId(TransactionIdLogPropertyName) .Enrich.FromMassTransit(); elasticSearchLogConfiguration .WriteTo.Elasticsearch(settings.Host, settings.IndexName); }); } // When in Development Mode, // Every and all logging will also be written to the trace and literate console, no matter what. // And since each logging pipeline excludes each other logging pipeline, // this should garantee that we will not have dupes into the Literate/Trace logging. if (IsDevelopment) { pipelineConfiguration .WriteTo.Trace(formatProvider: GetFormatProvider(logSettings.Culture)) .WriteTo.Console(formatProvider: GetFormatProvider(logSettings.Culture)); } return(pipelineConfiguration.CreateLogger()); }
public Startup(IConfiguration configuration) { Configuration = configuration; Serilog.Debugging.SelfLog.Enable(Console.WriteLine); /* * EmailConnectionInfo info = new EmailConnectionInfo() * { * EmailSubject = "Test Serilog: Using smtp.live.com", * FromEmail = "*****@*****.**", * MailServer = "smtp.live.com", * EnableSsl = true, * NetworkCredentials = new NetworkCredential("*****@*****.**", "acts15:23hot"), * Port = 587, * ToEmail = "*****@*****.**" * }; */ EmailConnectionInfo info = new EmailConnectionInfo() { EmailSubject = "Test Serilog: Using smtp.gmail.com", FromEmail = "*****@*****.**", MailServer = "smtp.gmail.com", // EnableSsl = true, NetworkCredentials = new NetworkCredential("*****@*****.**", "juDe3GOOG"), Port = 465, // 587 ToEmail = "*****@*****.**" }; /* Port = 465, MailServer = "smtp.gmail.com", EnableSsl = false * * [12:19:24 WRN] Starting web host: TrackMEDApi_Core * [12:19:24 INF] User profile is available. Using 'C:\Users\Julito\AppData\Local\ASP.NET\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest. * Hosting environment: Development * Content root path: C:\CIT\VS\Workspaces\RESMED\TrackMEDApi_Core\TrackMEDApi * Now listening on: https://localhost:5001 * Now listening on: http://localhost:5000 * Application started. Press Ctrl+C to shut down. * [12:19:27 INF] Request starting HTTP/1.1 GET http://localhost:5000/api/status * [12:19:27 INF] Request finished in 96.9392ms 307 * [12:19:27 INF] Request starting HTTP/1.1 GET https://localhost:5001/api/status * [12:19:27 INF] Executing endpoint 'TrackMEDApi.Controllers.StatusController.GetAllAsync (TrackMEDApi)' * [12:19:27 INF] Route matched with {action = "GetAllAsync", controller = "Status"}. Executing action TrackMEDApi.Controllers.StatusController.GetAllAsync (TrackMEDApi) * [12:19:28 INF] Executing action method TrackMEDApi.Controllers.StatusController.GetAllAsync (TrackMEDApi) - Validation state: Valid * [12:19:29 INF] Executed action method TrackMEDApi.Controllers.StatusController.GetAllAsync (TrackMEDApi), returned result Microsoft.AspNetCore.Mvc.ObjectResult in 814.7817ms. * [12:19:29 INF] Executing ObjectResult, writing value of type 'System.Collections.Generic.List`1[[TrackMEDApi.Models.Status, TrackMEDApi, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]'. * [12:19:29 INF] Executed action TrackMEDApi.Controllers.StatusController.GetAllAsync (TrackMEDApi) in 2115.8524ms * [12:19:29 INF] Executed endpoint 'TrackMEDApi.Controllers.StatusController.GetAllAsync (TrackMEDApi)' * [12:19:29 INF] Request finished in 2452.3145ms 200 application/json; charset=utf-8 * 2019-05-14T04:21:25.0526410Z Failed to send email: System.IO.IOException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond ---> System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond * at MailKit.Net.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 count) * --- End of inner exception stack trace --- * at MailKit.Net.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 count) * at MailKit.Net.Smtp.SmtpStream.ReadAheadAsync(Boolean doAsync, CancellationToken cancellationToken) * at MailKit.Net.Smtp.SmtpStream.ReadResponseAsync(Boolean doAsync, CancellationToken cancellationToken) * at MailKit.Net.Smtp.SmtpStream.ReadResponse(CancellationToken cancellationToken) * at MailKit.Net.Smtp.SmtpClient.ConnectAsync(String host, Int32 port, SecureSocketOptions options, Boolean doAsync, CancellationToken cancellationToken) * at MailKit.Net.Smtp.SmtpClient.Connect(String host, Int32 port, SecureSocketOptions options, CancellationToken cancellationToken) * at MailKit.MailService.Connect(String host, Int32 port, Boolean useSsl, CancellationToken cancellationToken) * at Serilog.Sinks.Email.EmailSink.OpenConnectedSmtpClient() * at Serilog.Sinks.Email.EmailSink.EmitBatchAsync(IEnumerable`1 events */ /* Port = 465 or 587, MailServer = "smtp.gmail.com", EnableSsl = true * * [12:32:35 WRN] Starting web host: TrackMEDApi_Core * [12:32:35 INF] User profile is available. Using 'C:\Users\Julito\AppData\Local\ASP.NET\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest. * 2019-05-14T04:32:36.3017572Z Failed to send email: MailKit.Security.SslHandshakeException: An error occurred while attempting to establish an SSL or TLS connection. * * One possibility is that you are trying to connect to a port which does not support SSL/TLS. * * The other possibility is that the SSL certificate presented by the server is not trusted by the system for one or more of the following reasons: * 1. The server is using a self-signed certificate which cannot be verified. * 2. The local system is missing a Root or Intermediate certificate needed to verify the server's certificate. * 3. The certificate presented by the server is expired or invalid. * * See https://github.com/jstedfast/MailKit/blob/master/FAQ.md#InvalidSslCertificate for possible solutions. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure. * at System.Net.Security.SslState.StartSendAuthResetSignal(ProtocolToken message, AsyncProtocolRequest asyncRequest, ExceptionDispatchInfo exception) * at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest) * at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest) * at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest) * at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest) * at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest) * at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest) * at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest) * at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest) * at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest) * at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest) * at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest) * at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest) * at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest) * at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest) * at System.Net.Security.SslState.PartialFrameCallback(AsyncProtocolRequest asyncRequest) * --- End of stack trace from previous location where exception was thrown --- * at System.Net.Security.SslState.ThrowIfExceptional() * at System.Net.Security.SslState.InternalEndProcessAuthentication(LazyAsyncResult lazyResult) * at System.Net.Security.SslState.EndProcessAuthentication(IAsyncResult result) at System.Net.Security.SslStream.EndAuthenticateAsClient(IAsyncResult asyncResult) * at System.Net.Security.SslStream.<>c.<AuthenticateAsClientAsync>b__46_2(IAsyncResult iar) * at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization) * --- End of stack trace from previous location where exception was thrown --- * at MailKit.Net.Smtp.SmtpClient.ConnectAsync(String host, Int32 port, SecureSocketOptions options, Boolean doAsync, CancellationToken cancellationToken) * --- End of inner exception stack trace --- * at MailKit.Net.Smtp.SmtpClient.ConnectAsync(String host, Int32 port, SecureSocketOptions options, Boolean doAsync, CancellationToken cancellationToken) * at MailKit.Net.Smtp.SmtpClient.Connect(String host, Int32 port, SecureSocketOptions options, CancellationToken cancellationToken) * at MailKit.MailService.Connect(String host, Int32 port, Boolean useSsl, CancellationToken cancellationToken) * at Serilog.Sinks.Email.EmailSink.OpenConnectedSmtpClient() * at Serilog.Sinks.Email.EmailSink.EmitBatchAsync(IEnumerable`1 events) * Hosting environment: Development * Content root path: C:\CIT\VS\Workspaces\RESMED\TrackMEDApi_Core\TrackMEDApi * Now listening on: https://localhost:5001 * Now listening on: http://localhost:5000 * Application started. Press Ctrl+C to shut down. * [12:32:38 INF] Request starting HTTP/1.1 GET http://localhost:5000/api/status * [12:32:38 INF] Request finished in 178.6448ms 307 * [12:32:39 INF] Request starting HTTP/1.1 GET https://localhost:5001/api/status * [12:32:39 INF] Executing endpoint 'TrackMEDApi.Controllers.StatusController.GetAllAsync (TrackMEDApi)' * [12:32:39 INF] Route matched with {action = "GetAllAsync", controller = "Status"}. Executing action TrackMEDApi.Controllers.StatusController.GetAllAsync (TrackMEDApi) * [12:32:40 INF] Executing action method TrackMEDApi.Controllers.StatusController.GetAllAsync (TrackMEDApi) - Validation state: Valid * [12:32:41 INF] Executed action method TrackMEDApi.Controllers.StatusController.GetAllAsync (TrackMEDApi), returned result Microsoft.AspNetCore.Mvc.ObjectResult in 1233.8136ms. * [12:32:41 INF] Executing ObjectResult, writing value of type 'System.Collections.Generic.List`1[[TrackMEDApi.Models.Status, TrackMEDApi, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]'. * [12:32:42 INF] Executed action TrackMEDApi.Controllers.StatusController.GetAllAsync (TrackMEDApi) in 2902.9024ms * [12:32:42 INF] Executed endpoint 'TrackMEDApi.Controllers.StatusController.GetAllAsync (TrackMEDApi)' * [12:32:42 INF] Request finished in 3262.0194ms 200 application/json; charset=utf-8 * */ // Configure Serilog // Version 1: Using AppSettings (Serilog) Log.Logger = new LoggerConfiguration() .ReadFrom.Configuration(Configuration) .WriteTo.Console() /* * .WriteTo.Email(info, * outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}", * restrictedToMinimumLevel: LogEventLevel.Warning) // https://github.com/serilog/serilog/wiki/Configuration-Basics#overriding-per-sink * * .WriteTo.Email(new EmailConnectionInfo * { * FromEmail = "*****@*****.**", * ToEmail = "*****@*****.**", * MailServer = "smtp.live.com", * NetworkCredentials = new NetworkCredential * { * UserName = "******", * Password = "******" * }, * EnableSsl = true, * Port = 587, * EmailSubject = "Test Serilog" * }, * outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}" * // batchPostingLimit: 10 * , restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Warning * ) */ .CreateLogger(); // Version 2: Ignoring AppSettings /* var uriMongoDB = Configuration.GetValue<string>("MongoSettings:mongoconnection"); * Log.Logger = new LoggerConfiguration() * .MinimumLevel.Warning() * .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) * .Enrich.FromLogContext() * .WriteTo.Console() * .WriteTo.MongoDBCapped(uriMongoDB, collectionName: "logsTrackMEDApi") // https://github.com/serilog/serilog-sinks-mongodb * .CreateLogger(); */ Log.Warning("Starting web host: TrackMEDApi_Core"); }