本文整理汇总了C#中Serilog.LoggerConfiguration.CreateLogger方法的典型用法代码示例。如果您正苦于以下问题:C# LoggerConfiguration.CreateLogger方法的具体用法?C# LoggerConfiguration.CreateLogger怎么用?C# LoggerConfiguration.CreateLogger使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Serilog.LoggerConfiguration
的用法示例。
在下文中一共展示了LoggerConfiguration.CreateLogger方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
static void Main(string[] args)
{
Console.WriteLine("I'm ALIVE!");
var loggerConfiguration = new LoggerConfiguration()
.WriteTo.ColoredConsole()
.Enrich.WithMachineName()
.MinimumLevel.Debug();
var logger = loggerConfiguration.CreateLogger();
Log.Logger = logger;
Log.Information("Starting up. Testing out all things C# 6.");
var sleepPeriodInSeconds = 60;
if (args.Length > 0 && int.TryParse(args[0], out sleepPeriodInSeconds))
{
Log.Information("Sleep interval provided. Setting sleep period {SleepPeriodInSeconds}.", sleepPeriodInSeconds);
}
var sleepPeriod = TimeSpan.FromSeconds(sleepPeriodInSeconds);
Log.Information("EC2 Host information, if any. {@Ec2MetaData}", Ec2MetaData.Create());
while (true)
{
var coinToss = Random.Next(0, 2);
Log.Information("Coin Toss... {CoinToss}", coinToss);
var instance = coinToss == 0 ? new WithPropertyInit() : null;
Log.Information("Doing Work... {NameOfProp}", instance?.NameOfProp());
Log.Information("{@Instance}", instance);
Thread.Sleep(sleepPeriod);
}
}
示例2: Application_Start
protected void Application_Start()
{
RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
RouteTable.Routes.LowercaseUrls = true;
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
var Logger = new LoggerConfiguration()
.WriteTo.Seq(Properties.Settings.Default.SeqLogUrl, apiKey: Properties.Settings.Default.SeqLogKey, bufferBaseFilename: AppDomain.CurrentDomain.BaseDirectory + @"App_Data\Logs")
.Enrich.WithMachineName()
.Enrich.With<HttpRequestUrlEnricher>()
.Enrich.WithThreadId()
.Enrich.With<HttpRequestClientHostIPEnricher>()
.Enrich.WithProcessId()
.Enrich.With<HttpRequestIdEnricher>()
.Enrich.With<HttpRequestTypeEnricher>()
.Enrich.With<HttpRequestUserAgentEnricher>()
.Enrich.With<HttpRequestUrlReferrerEnricher>();
Log.Logger = Logger.CreateLogger();
Log.Debug("Address API started.");
}
示例3: Configure
public static void Configure()
{
var logConfig = new LoggerConfiguration()
.WriteTo.SignalR(GlobalHost.ConnectionManager.GetHubContext<LoggingHub>());
Log.Logger = logConfig.CreateLogger();
}
示例4: GetLogger
public ILogger GetLogger()
{
var loggerConfig = new LoggerConfiguration()
.WriteTo.ColoredConsole(LogEventLevel.Debug)
.Enrich.With(new ProcessIdEnricher());
return loggerConfig.CreateLogger();
}
示例5: Load
protected override void Load(ContainerBuilder builder)
{
//Register components here
builder.RegisterType<Service>().As<IService>();
builder.RegisterType<WindowsService>().As<ServiceControl>();
builder.RegisterType<OwinStartup>().As<IOwinStartup>();
builder.RegisterType<NancyBootstrapper>().As<INancyBootstrapper>();
builder.RegisterType<Config>().As<IConfig>();
var loggerConfiguration = new LoggerConfiguration()
.Enrich.WithThreadId() //Add threadId for each log entry
.Enrich.FromLogContext() //Allow to add context values
.Enrich.WithProperty("RuntimeVersion", Environment.Version)
.WriteTo.FileSinkDefinedFromConfig();
Log.Logger = loggerConfiguration.CreateLogger();
builder.RegisterInstance(Log.Logger).As<ILogger>();
builder.RegisterType<RequeueAndRemove>().As<IRequeueAndRemove>();
builder.RegisterType<BusMonitor>().As<IBusMonitor>().SingleInstance();
builder.RegisterType<Sender>().As<ISender>().SingleInstance();
builder.Register(c => NamespaceManager.CreateFromConnectionString(c.Resolve<IConfig>().BusConnectionString)).As<NamespaceManager>();
builder.Register(c => MessagingFactory.CreateFromConnectionString(c.Resolve<IConfig>().BusConnectionString)).As<MessagingFactory>();
builder.RegisterType<BusManagerModule>().AsSelf().AsImplementedInterfaces();
builder.RegisterAllImplementationsInAssembly<IModelBuilderBase>(typeof(QueueMessagesBuilder).Assembly);
builder.RegisterAllImplementationsInAssembly<ICommandHandlerBase>(typeof(RequeueMessageCommandHandler).Assembly);
}
示例6: TestWithSerilog
/// <summary>
/// Initializes a new instance of the <see cref="TestWithSerilog"/> class.
/// </summary>
/// <param name="output">
/// The Xunit output.
/// </param>
protected TestWithSerilog(ITestOutputHelper output)
{
var loggerConfig = new LoggerConfiguration()
.MinimumLevel.Verbose()
.WriteTo.TextWriter(new XunitOutputWriter(output));
Logger = loggerConfig.CreateLogger();
}
示例7: Logging
public static ILogger Logging()
{
ApplicationLifecycleModule.IsEnabled = false;
var assemblyName = Constants.WebAssembly.GetName().Name;
var assemblyVersion = Constants.WebAssembly.GetName().Version;
var minimumLogLevel = DefaultSettingsReader.Get<MinimumLogLevelSetting>();
var environment = DefaultSettingsReader.Get<EnvironmentSetting>();
var seqServerUri = DefaultSettingsReader.Get<SeqServerUriSetting>();
var loggerConfig = new LoggerConfiguration()
.MinimumLevel.Is(minimumLogLevel)
.Enrich.FromLogContext()
.Enrich.WithMachineName()
.Enrich.WithThreadId()
.Enrich.With<HttpRequestIdEnricher>()
.Enrich.WithProperty("ApplicationName", assemblyName)
.Enrich.WithProperty("ApplicationVersion", assemblyVersion)
.Enrich.WithProperty("Environment", environment)
.WriteTo.Seq(seqServerUri.ToString())
.WriteTo.Trace();
return loggerConfig.CreateLogger();
}
示例8: ConfigureLogging
/// <summary>
/// Create and return a serilog ILogger instance.
/// For convenience this also sets the global Serilog.Log instance
/// </summary>
/// <returns></returns>
public static ILogger ConfigureLogging()
{
var loggerConfig = new LoggerConfiguration()
//Enrich each log message with the machine name
.Enrich.With<MachineNameEnricher>()
//Accept verbose output (there is effectively no filter)
.MinimumLevel.Verbose()
//Write out to the console using the "Literate" console sink (colours the text based on the logged type)
.WriteTo.LiterateConsole()
//Also write out to a file based on the date and restrict these writes to warnings or worse (warning, error, fatal)
.WriteTo.RollingFile(@"Warnings_{Date}.txt", global::Serilog.Events.LogEventLevel.Warning);
if (useSeq)
{
//Send events to a default installation of Seq on the local computer
loggerConfig = loggerConfig.WriteTo.Seq("http://localhost:5341");
}
var logger = loggerConfig
//Take all of that configuration and make a logger
.CreateLogger();
//Stash the logger in the global Log instance for convenience
global::Serilog.Log.Logger = logger;
return logger;
}
示例9: RegisterApplication
static ContainerBuilder RegisterApplication(IProgramOptions options)
{
var builder = new ContainerBuilder();
builder.RegisterInstance(options).As<IProgramOptions>();
var logConfig = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.ColoredConsole();
builder.RegisterModule<LogicIocModule>();
if (options.Interactive)
{
builder.RegisterModule(new ConsoleIocModule(logConfig));
builder.RegisterType<ConsoleApplication>().As<IApplication>().SingleInstance();
}
else
{
builder.RegisterModule(new WebAppIocModule(logConfig));
builder.RegisterType<WebApplication>().As<IApplication>().SingleInstance();
}
Log.Logger = logConfig.CreateLogger();
builder.RegisterInstance(Log.Logger).As<ILogger>();
return builder;
}
示例10: Main
/// <summary>
/// Service main entry point
/// </summary>
/// <param name="args">
/// Startup parameters
/// </param>
public static void Main(string[] args)
{
// preset logger
var loggerConfig = new LoggerConfiguration().MinimumLevel.Debug().WriteTo.ColoredConsole();
var logger = loggerConfig.CreateLogger();
Log.Logger = logger;
var arguments = new Docopt().Apply(CommandUsage, args, exit: true);
var configurations = new List<string>();
ValueObject config;
if (arguments.TryGetValue("--config", out config) && config != null)
{
configurations.Add(config.ToString());
}
Container = new WindsorContainer();
AppDomain.CurrentDomain.UnhandledException += (sender, eventArgs) =>
{
Log.Logger.Error(
eventArgs.ExceptionObject as Exception,
"{Type}: Unhandled domain exception from {SenderType}, terminating: {IsTerminating}\n{StackTrace}",
"System",
sender?.GetType().Name ?? "unknown",
eventArgs.IsTerminating,
(eventArgs.ExceptionObject as Exception)?.StackTrace);
};
var system = Bootstrapper.ConfigureAndStart(Container, configurations.ToArray());
Log.Logger.Warning("{Type}: Started", "System");
Console.CancelKeyPress += (sender, eventArgs) =>
{
Log.Logger.Warning("{Type}: Shutdown sequence initiated", "System");
var cluster = Akka.Cluster.Cluster.Get(system);
var timeout = TimeSpan.FromSeconds(10);
if (cluster.IsTerminated || cluster.State.Members.Count == 0)
{
system.Terminate().Wait(timeout);
}
else
{
cluster.LeaveAsync().Wait(timeout);
system.Terminate().Wait(timeout);
}
Log.Logger.Warning("{Type}: Hard stopped", "System");
eventArgs.Cancel = true;
};
system.StartNameSpaceActorsFromConfiguration();
BaseInstaller.RunPostStart(Container);
var waitedTask = new System.Threading.Tasks.TaskCompletionSource<bool>();
system.WhenTerminated.ContinueWith(task => waitedTask.SetResult(true));
waitedTask.Task.Wait();
Log.Logger.Warning("{Type}: Stopped", "System");
}
示例11: CreateLogger
public static ILogger CreateLogger()
{
var config = new LoggerConfiguration();
config
.MinimumLevel.ControlledBy(new LoggingLevelSwitch { MinimumLevel = LogEventLevel.Debug })
.WriteTo.ColoredConsole()
.WriteTo.Trace();
return config.CreateLogger();
}
示例12: Load
protected override void Load(ContainerBuilder builder)
{
var configuration = new LoggerConfiguration()
.ReadFrom.AppSettings()
.Enrich.With<ThreadIdEnricher>();
Log.Logger = configuration.CreateLogger();
// configure Log to return our Serilog logger abstraction
Core.Logging.Log.Customize(type => new SerilogLogger(Log.ForContext(type)));
}
示例13: ConfigureLogging
private static void ConfigureLogging()
{
var loggingConfig = new LoggerConfiguration().WriteTo.ColoredConsole();
if (!string.IsNullOrEmpty(StaticConfiguration.LoggingEndpoint))
{
loggingConfig.WriteTo.Seq(StaticConfiguration.LoggingEndpoint);
}
Log.Logger = loggingConfig.CreateLogger();
}
示例14: Main
public static void Main()
{
SelfLog.Out = Console.Out;
var client = new AmazonKinesisClient();
var streamOk = KinesisApi.CreateAndWaitForStreamToBecomeAvailable(
kinesisClient: client,
streamName: streamName,
shardCount: shardCount
);
var loggerConfig = new LoggerConfiguration()
.WriteTo.ColoredConsole()
.MinimumLevel.Debug();
if (streamOk)
{
loggerConfig.WriteTo.AmazonKinesis(
kinesisClient: client,
streamName: streamName,
shardCount: shardCount,
period: TimeSpan.FromSeconds(2),
bufferBaseFilename: "./logs/kinesis-buffer",
onLogSendError: OnLogSendError
);
}
Log.Logger = loggerConfig.CreateLogger();
#if false
for (var i = 0; i < 50; i++)
{
for (int j = 0; j < 500; j++)
{
Thread.Sleep(1);
Log.Debug("Count: {i} {j}", i, j);
}
Console.Write(".");
}
#endif
LogStuff();
Log.Fatal("That's all folks - and all done using {WorkingSet} bytes of RAM", Environment.WorkingSet);
Console.ReadKey();
}
示例15: CreateLog
public static ILogger CreateLog()
{
//log messages can get pretty big, so it's nice to have a lot of space to view them:
Console.WindowWidth = (int)(Console.LargestWindowWidth * 0.75);
Console.BufferWidth = 300; //for extra long messages
Console.WindowHeight = (int)(Console.LargestWindowHeight * 0.75);
Console.BufferHeight = 2000; //so everything is visible
var config = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.ColoredConsole(LogEventLevel.Debug);
return config.CreateLogger();
}