本文整理汇总了C#中Serilog.LoggerConfiguration类的典型用法代码示例。如果您正苦于以下问题:C# LoggerConfiguration类的具体用法?C# LoggerConfiguration怎么用?C# LoggerConfiguration使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
LoggerConfiguration类属于Serilog命名空间,在下文中一共展示了LoggerConfiguration类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Configure
/// <summary>
/// Performs configuration
/// </summary>
/// <param name="configuration">Previous configuration</param>
/// <param name="config">Akka configuration</param>
/// <returns>Updated configuration</returns>
public LoggerConfiguration Configure(LoggerConfiguration configuration, Config config)
{
var minimumLevel = config.GetString("ClusterKit.Log.ElasticSearch.minimumLevel", "none")?.Trim();
LogEventLevel level;
if (!Enum.TryParse(minimumLevel, true, out level))
{
return configuration;
}
var nodes = config.GetStringList("ClusterKit.Log.ElasticSearch.nodes");
var indexFormat = config.GetString("ClusterKit.Log.ElasticSearch.indexFormat", "logstash-{0:yyyy.MM.dd}");
Log.Information(
"{Type}: \n\tMinimum level: {MinimumLevel}\n\tIndex format: {IndexFormat}\n\tNodes:\n\t\t{NodeList}\n",
this.GetType().FullName,
minimumLevel,
indexFormat,
string.Join("\n\t\t", nodes));
SelfLog.Enable(Console.WriteLine);
var options = new ElasticsearchSinkOptions(nodes.Select(s => new Uri(s)))
{
MinimumLogEventLevel = level,
AutoRegisterTemplate = true,
IndexFormat = indexFormat
};
return configuration.WriteTo.Elasticsearch(options);
}
示例2: 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;
}
示例3: BaseSetup
public void BaseSetup()
{
LogOutput = new StringBuilder();
Log = new LoggerConfiguration()
.WriteTo.TextWriter(new StringWriter(LogOutput), outputTemplate: "[{Level}] {Message}{NewLine}{Exception}", formatProvider: new StringFormatter(null))
.CreateLogger();
RootResource rootDocument = Substitute.For<RootResource>();
rootDocument.ApiVersion = "2.0";
rootDocument.Version = "2.0";
rootDocument.Links.Add("Tenants", "http://tenants.org");
Repository = Substitute.For<IOctopusAsyncRepository>();
Repository.Client.RootDocument.Returns(rootDocument);
ClientFactory = Substitute.For<IOctopusClientFactory>();
RepositoryFactory = Substitute.For<IOctopusAsyncRepositoryFactory>();
RepositoryFactory.CreateRepository(null).ReturnsForAnyArgs(Repository);
FileSystem = Substitute.For<IOctopusFileSystem>();
CommandLineArgs = new List<string>
{
"--server=http://the-server",
"--apiKey=ABCDEF123456789"
};
}
示例4: 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);
}
}
示例5: WorkflowRegistry
public WorkflowRegistry()
{
For<IRepository<Crisis>>().Use<CrisisRepository>();
var logFolder = ConfigurationManager.AppSettings["LogFolder"] + @"\Log-{Date}.txt";
var logger = new LoggerConfiguration().WriteTo.RollingFile(logFolder).CreateLogger();
For<ILogger>().Use(x => logger);
}
示例6: FinishedLaunching
//
// This method is invoked when the application has loaded and is ready to run. In this
// method you should instantiate the window, load the UI into it and then make the window
// visible.
//
// You have 17 seconds to return from this method, or iOS will terminate your application.
//
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
Current = this;
var log = new LoggerConfiguration().CreateLogger();
log.Information("Loading");
UIApplication.SharedApplication.StatusBarStyle = UIStatusBarStyle.LightContent;
// create a new window instance based on the screen size
window = new UIWindow(UIScreen.MainScreen.Bounds);
// If you have defined a view, add it here:
// window.RootViewController = navigationController;
var rootNavigationController = Utilities.BuildNavigationController();
rootNavigationController.PushViewController(new ViewControllers.Login(), false);
window.RootViewController = rootNavigationController;
// make the window visible
window.MakeKeyAndVisible();
Utilities.SetTintColor();
autoSuspendHelper.FinishedLaunching(app, options);
return true;
}
示例7: Run
public override void Run()
{
var cs = CloudConfigurationManager.GetSetting("StorageConnectionString");
CloudStorageAccount storageAccount;
CloudStorageAccount.TryParse(cs, out storageAccount);
var log = new LoggerConfiguration().WriteTo.AzureTableStorage(storageAccount).CreateLogger();
log.Information("Who let azure out");
log.Information("Starting processing of messages");
// Initiates the message pump and callback is invoked for each message that is received, calling close on the client will stop the pump.
_client.OnMessage((receivedMessage) =>
{
try
{
// Process the message
Trace.WriteLine("Processing Service Bus message: " + receivedMessage.SequenceNumber.ToString());
}
catch(Exception e)
{
// Handle any message processing specific exceptions here
}
});
_completedEvent.WaitOne();
}
示例8: Configure
/// <summary>
/// Performs configuration
/// </summary>
/// <param name="configuration">Previous configuration</param>
/// <param name="config">Akka configuration</param>
/// <returns>Updated configuration</returns>
public LoggerConfiguration Configure(LoggerConfiguration configuration, Config config)
{
var templateName = config.GetString("ClusterKit.NodeManager.NodeTemplate");
return string.IsNullOrWhiteSpace(templateName)
? configuration
: configuration.Enrich.WithProperty("nodeTemplate", templateName);
}
示例9: Startup
public Startup(
IHostingEnvironment hostingEnvironment,
ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger<Startup>();
var configuration = new Configuration();
configuration.AddJsonFile("config.json");
configuration.AddEnvironmentVariables();
var loggingConfiguration = configuration.GetSubKey("Logging");
var serilog = new LoggerConfiguration()
.MinimumLevel.Verbose()
.Enrich.WithMachineName()
.Enrich.WithProcessId()
.Enrich.WithThreadId();
if (string.Equals(hostingEnvironment.EnvironmentName, "Development", StringComparison.OrdinalIgnoreCase))
{
serilog.WriteTo.ColoredConsole();
}
string elasticSearchConnectionString;
if (loggingConfiguration.TryGet("ElasticSearch:Server", out elasticSearchConnectionString))
{
serilog.WriteTo.ElasticSearch(node: new Uri(elasticSearchConnectionString));
}
loggerFactory.AddSerilog(serilog);
}
示例10: 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);
}
示例11: Configure
public static void Configure()
{
var logConfig = new LoggerConfiguration()
.WriteTo.SignalR(GlobalHost.ConnectionManager.GetHubContext<LoggingHub>());
Log.Logger = logConfig.CreateLogger();
}
示例12: SetupContainer
public static void SetupContainer()
{
// Create User
var user = new CurrentUser() { Username = "GDP1", LabCode = "EUHAWE3" };
// Create Logger
var logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.MinimumLevel.Warning() // Set MinimumLevel of Warning
.WriteTo.Seq("http://localhost:5341")
.CreateLogger();
unityContainer = new UnityContainer();
// Register User
unityContainer.RegisterInstance<ICurrentUser>(user);
// Add Interception Extension
unityContainer.AddNewExtension<Microsoft.Practices.Unity.InterceptionExtension.Interception>();
//Register Logger Instance
unityContainer.RegisterInstance<ILogger>(logger);
unityContainer.RegisterType<ISamRepository, SamRepository>()
.Configure<Microsoft.Practices.Unity.InterceptionExtension.Interception>()
.SetInterceptorFor<ISamRepository>(
new InterfaceInterceptor());
}
示例13: Application_Start
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
// Apply the HandleException attribute to all MVC controllers.
// It extends the MVC HandleError attribute so that it catches HTTP errors with status 500 and displays them nicely
// instead of defaulting to the IIS error page.
GlobalFilters.Filters.Add(new CustomHandleError());
// Apply the CustomAuthorize filter to all MVC controllers.
// It extends the MVC Authorize attribute to take care of role-checking and making sure user accounts have not been disabled.
// To prevent a controller from needing authentication and authorization (like AccountController), use [AllowAnonymous].
// To enforce a role on an MVC controller or action, use [CustomAuthorize(Roles = "admin")].
GlobalFilters.Filters.Add(new CustomAuthorize());
// Apply the CustomApiAuthorize filter to all API controllers.
// It extends the API Authorize attribute to take care of role-checking and making sure user accounts have not been disabled.
// To enforce a role on an API controller or action, use [CustomApiAuthorize(Roles = "admin")].
GlobalConfiguration.Configuration.Filters.Add(new CustomApiAuthorize());
// Apply the ValidateApiModel attribute to all API controllers.
// It extends the ActionFilterAttribute to perform model validation on DTOs that use the System.DataComponents.DataAnnotations annotations.
// If the model does not validate, it returns a 400 Bad Request with error messages specified in the annotations.
GlobalConfiguration.Configuration.Filters.Add(new ValidateApiModelAttribute());
// Serilog.
using (var log = new LoggerConfiguration().ReadFrom.AppSettings().CreateLogger())
{
log.Information("Application_Start: the SLLInvoices application has started");
}
}
示例14: ConfigureLogging
private static void ConfigureLogging(ContainerBuilder containerBuilder)
{
//var endpoint = new Uri(ConfigurationManager.AppSettings.Get("DocumentDbEndpoint"));
//var seed = ConfigurationManager.AppSettings.Get("DocumentDbSeed");
//ILogger seriLogger;
//try
//{
// seriLogger = new LoggerConfiguration()
// .WriteTo.AzureDocumentDB(endpoint, seed)
// .WriteTo.RollingFile("CheckSwpProject.log")
// .CreateLogger();
//}
//catch (Exception)
//{
// seriLogger = new LoggerConfiguration()
// .WriteTo.RollingFile("CheckSwpProject.log")
// .CreateLogger();
//}
var seriLogger = new LoggerConfiguration()
.WriteTo.RollingFile("CheckSwpProject.log")
.CreateLogger();
var consoleLogger = new ConsoleLogger(seriLogger);
containerBuilder.RegisterInstance(consoleLogger).As<ILoggerFacade>().SingleInstance();
}
示例15: OrleansTestActorService
public OrleansTestActorService(StatelessServiceContext context)
: base(context)
{
var esLogsConfig = new FabricConfigProvider<ElasticSearchOutputConfig>("ElasticSearchLogs").Config;
var esMetricsConfig = new FabricConfigProvider<ElasticSearchOutputConfig>("ElasticSearchMetrics").Config;
var logger = new LoggerConfiguration()
.MinimumLevel.Verbose()
.Enrich.With(new AzureServiceFabricSerilogEnricher(context))
.Enrich.With<ExceptionEnricher>()
.Enrich.With<ActivityIdSerilogEnricher>()
.WriteTo.Elasticsearch(
new ElasticsearchSinkOptions(new Uri(esLogsConfig.ElasticSearchUri))
{
IndexFormat = $"{esLogsConfig.ElasticSearchIndexName}-{{0:yyyy.MM.dd}}"
})
.CreateLogger();
Log.Logger = logger;
//Metric.Config.WithAllCounters();
_disposable = new TelemetryPipe()
.CollectMetricsNet(10, ServiceFabricHelpers.GetEnvironmentProperties(context), true)
.SendToElasticSearch(esMetricsConfig)
.Start();
TraceLogger.BulkMessageInterval = TimeSpan.FromSeconds(10);
Logger.TelemetryConsumers.Add(new SerilogTelemetryConsumer());
Logger.TelemetryConsumers.Add(new MetricNetTelemetryConsumer());
}