本文整理汇总了C#中LoggerConfiguration类的典型用法代码示例。如果您正苦于以下问题:C# LoggerConfiguration类的具体用法?C# LoggerConfiguration怎么用?C# LoggerConfiguration使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
LoggerConfiguration类属于命名空间,在下文中一共展示了LoggerConfiguration类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: TestRollingEventSequence
static void TestRollingEventSequence(
IEnumerable<LogEvent> events,
int? retainedFiles,
Action<IList<string>> verifyWritten)
{
var fileName = Some.String() + "-{Date}.txt";
var folder = Some.TempFolderPath();
var pathFormat = Path.Combine(folder, fileName);
var log = new LoggerConfiguration()
.WriteTo.RollingFile(pathFormat, retainedFileCountLimit: retainedFiles)
.CreateLogger();
var verified = new List<string>();
try
{
foreach (var @event in events)
{
Clock.SetTestDateTimeNow(@event.Timestamp.DateTime);
log.Write(@event);
var expected = pathFormat.Replace("{Date}", @event.Timestamp.ToString("yyyyMMdd"));
Assert.That(File.Exists(expected));
verified.Add(expected);
}
}
finally
{
((IDisposable)log).Dispose();
verifyWritten(verified);
Directory.Delete(folder, true);
}
}
开发者ID:NikolaR,项目名称:serilog,代码行数:35,代码来源:RollingFileSinkTests.cs
示例2: TestRollingEventSequence
static void TestRollingEventSequence(params LogEvent[] events)
{
var fileName = Some.String() + "{0}.txt";
var folder = Some.TempFolderPath();
var pathFormat = Path.Combine(folder, fileName);
var log = new LoggerConfiguration()
.WriteTo.RollingFile(pathFormat)
.CreateLogger();
try
{
foreach (var @event in events)
{
log.Write(@event);
var expected = string.Format(pathFormat, @event.Timestamp.ToString("yyyy-MM-dd"));
Assert.That(System.IO.File.Exists(expected));
}
}
finally
{
((IDisposable)log).Dispose();
Directory.Delete(folder, true);
}
}
开发者ID:robdmoore,项目名称:serilog,代码行数:26,代码来源:RollingFileSinkTests.cs
示例3: LoggerSinkConfiguration
internal LoggerSinkConfiguration(LoggerConfiguration loggerConfiguration, Action<ILogEventSink> addSink)
{
if (loggerConfiguration == null) throw new ArgumentNullException("loggerConfiguration");
if (addSink == null) throw new ArgumentNullException("addSink");
_loggerConfiguration = loggerConfiguration;
_addSink = addSink;
}
开发者ID:nicholaspei,项目名称:serilog,代码行数:7,代码来源:LoggerSinkConfiguration.cs
示例4: UsingSuperLongLogMessageWorks
public void UsingSuperLongLogMessageWorks()
{
var charcounts = new[]
{
10*1000,
20*1000,
30*1000,
40*1000,
70*1000
};
foreach (var charcount in charcounts)
{
var log = new LoggerConfiguration()
.WriteTo.EventLog("EventLogSinkTests")
.CreateLogger();
var guid = Guid.NewGuid().ToString("D");
log.Information("This is a super long message which might be trimmed. Guid is {Guid}.The following text has {charcount} chars: {LongText}"
, guid
, charcount
, new string('x', charcount));
Assert.IsTrue(EventLogMessageWithSpecificBodyExists(guid), "The message was not found in the eventlog. Charcount was " + charcount);
}
}
开发者ID:modulexcite,项目名称:serilog-sinks-eventlog,代码行数:25,代码来源:EventLogSinkTests.cs
示例5: MoreNestedPropertiesOverrideLessNestedOnes
public void MoreNestedPropertiesOverrideLessNestedOnes()
{
LogEvent lastEvent = null;
var log = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Sink(new DelegatingSink(e => lastEvent = e))
.CreateLogger();
using (LogContext.PushProperty("A", 1))
{
log.Write(Some.InformationEvent());
Assert.AreEqual(1, lastEvent.Properties["A"].LiteralValue());
using (LogContext.PushProperty("A", 2))
{
log.Write(Some.InformationEvent());
Assert.AreEqual(2, lastEvent.Properties["A"].LiteralValue());
}
log.Write(Some.InformationEvent());
Assert.AreEqual(1, lastEvent.Properties["A"].LiteralValue());
}
log.Write(Some.InformationEvent());
Assert.IsFalse(lastEvent.Properties.ContainsKey("A"));
}
开发者ID:nberardi,项目名称:serilog,代码行数:27,代码来源:LogContextTests.cs
示例6: LoggerMinimumLevelConfiguration
internal LoggerMinimumLevelConfiguration(LoggerConfiguration loggerConfiguration, Action<LogEventLevel> setMinimum)
{
if (loggerConfiguration == null) throw new ArgumentNullException("loggerConfiguration");
if (setMinimum == null) throw new ArgumentNullException("setMinimum");
_loggerConfiguration = loggerConfiguration;
_setMinimum = setMinimum;
}
开发者ID:nicholaspei,项目名称:serilog,代码行数:7,代码来源:LoggerMinimumLevelConfiguration.cs
示例7: AttributesAreConsultedWhenDestructuring
public void AttributesAreConsultedWhenDestructuring()
{
LogEvent evt = null;
var log = new LoggerConfiguration()
.Destructure.UsingAttributes()
.WriteTo.Sink(new DelegatingSink(e => evt = e))
.CreateLogger();
var customized = new Customized
{
ImmutableScalar = new ImmutableScalar(),
MutableScalar = new MutableScalar(),
NotAScalar = new NotAScalar(),
Ignored = "Hello, there",
ScalarAnyway = new NotAScalar()
};
log.Information("Here is {@Customized}", customized);
var sv = (StructureValue)evt.Properties["Customized"];
var props = sv.Properties.ToDictionary(p => p.Name, p => p.Value);
Assert.IsInstanceOf<ImmutableScalar>(props["ImmutableScalar"].LiteralValue());
Assert.AreEqual(new MutableScalar().ToString(), props["MutableScalar"].LiteralValue());
Assert.IsInstanceOf<StructureValue>(props["NotAScalar"]);
Assert.IsFalse(props.ContainsKey("Ignored"));
Assert.IsInstanceOf<NotAScalar>(props["ScalarAnyway"].LiteralValue());
}
开发者ID:BugBusted,项目名称:serilog,代码行数:29,代码来源:AttributedDestructuringTests.cs
示例8: LoggingLevelSwitchDynamicallyChangesLevel
public void LoggingLevelSwitchDynamicallyChangesLevel()
{
var events = new List<LogEvent>();
var sink = new DelegatingSink(events.Add);
var levelSwitch = new LoggingLevelSwitch(LogEventLevel.Information);
var log = new LoggerConfiguration()
.MinimumLevel.ControlledBy(levelSwitch)
.WriteTo.Sink(sink)
.CreateLogger()
.ForContext<LoggerTests>();
log.Debug("Suppressed");
log.Information("Emitted");
log.Warning("Emitted");
// Change the level
levelSwitch.MinimumLevel = LogEventLevel.Error;
log.Warning("Suppressed");
log.Error("Emitted");
log.Fatal("Emitted");
Assert.Equal(4, events.Count);
Assert.True(events.All(evt => evt.RenderMessage() == "Emitted"));
}
开发者ID:serilog,项目名称:serilog,代码行数:27,代码来源:LoggerTests.cs
示例9: ContextPropertiesCrossAsyncCalls
public async Task ContextPropertiesCrossAsyncCalls()
{
LogEvent lastEvent = null;
var log = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Sink(new DelegatingSink(e => lastEvent = e))
.CreateLogger();
using (LogContext.PushProperty("A", 1))
{
var pre = Thread.CurrentThread.ManagedThreadId;
await Task.Delay(1000);
var post = Thread.CurrentThread.ManagedThreadId;
log.Write(Some.InformationEvent());
Assert.AreEqual(1, lastEvent.Properties["A"].LiteralValue());
// No problem if this happens occasionally.
if (pre == post)
Assert.Inconclusive("The test was marshalled back to the same thread after awaiting");
}
}
开发者ID:nberardi,项目名称:serilog,代码行数:25,代码来源:LogContextTests.cs
示例10: RunAsync
async protected override Task RunAsync(CancellationToken cancellationToken)
{
var esLogsConfig = new FabricConfigProvider<ElasticSearchOutputConfig>("ElasticSearchLogs").Config;
var esMetricsConfig = new FabricConfigProvider<ElasticSearchOutputConfig>("ElasticSearchMetrics").Config;
var logger = new LoggerConfiguration()
.ConfigureMOUSETypesDestructure()
.MinimumLevel.Warning()
.Enrich.With(new AzureServiceFabricSerilogEnricher(Context))
.Enrich.With<ExceptionEnricher>()
.WriteTo.Elasticsearch(
new ElasticsearchSinkOptions(new Uri(esLogsConfig.ElasticSearchUri))
{
IndexFormat = $"{esLogsConfig.ElasticSearchIndexName}-{{0:yyyy.MM.dd}}"
})
.CreateLogger();
Log.Logger = logger;
Metric.Config.WithAllCounters();
//Metric.PerformanceCounter("Actor calls waiting for actor lock", "Service Fabric Actor", "# of actor calls waiting for actor lock", "*", Unit.Items);
//Metric.PerformanceCounter("Actor outstanding requests", "Service Fabric Actor", "# of outstanding requests", "*", Unit.Items);
//Metric.PerformanceCounter("Actor Average milliseconds actor lock held", "Service Fabric Actor", "Average milliseconds actor lock held", "*", Unit.Custom("ms"));
//Metric.PerformanceCounter("Actor Average milliseconds for request deserialization", "Service Fabric Actor", "Average milliseconds for request deserialization", "*", Unit.Custom("ms"));
//Metric.PerformanceCounter("Actor Average milliseconds for response serialization", "Service Fabric Actor", "Average milliseconds for response serialization", "*", Unit.Custom("ms"));
//Metric.PerformanceCounter("Actor Average milliseconds per load state operation", "Service Fabric Actor", "Average milliseconds per load state operation", "*", Unit.Custom("ms"));
//Metric.PerformanceCounter("Actor Average milliseconds per lock wait", "Service Fabric Actor", "Average milliseconds per lock wait", "*", Unit.Custom("ms"));
//Metric.PerformanceCounter("Actor Average milliseconds per request", "Service Fabric Actor", "Average milliseconds per request", "*", Unit.Custom("ms"));
//Metric.PerformanceCounter("Actor Average milliseconds per save state operation", "Service Fabric Actor", "Average milliseconds per save state operation", "*", Unit.Custom("ms"));
//Metric.PerformanceCounter("Actor Average OnActivateAsync milliseconds", "Service Fabric Actor", "Average OnActivateAsync milliseconds", "*", Unit.Custom("ms"));
//Metric.PerformanceCounter("Actor Method Average milliseconds per invocation", "Service Fabric Actor Method", "Average milliseconds per invocation", "*", Unit.Custom("ms"));
//Metric.PerformanceCounter("Actor Method Exceptions thrown/Sec", "Service Fabric Actor Method", "Exceptions thrown/Sec", "*", Unit.Custom("rate/sec"));
//Metric.PerformanceCounter("Actor Method Invocations/Sec", "Service Fabric Actor Method", "Invocations/Sec", "*", Unit.Custom("rate/sec"));
var metricsSubscription = new TelemetryPipe()
.CollectMetricsNet(5, ServiceFabricHelpers.GetEnvironmentProperties(Context), true)
.SendToElasticSearch(esMetricsConfig)
.Start();
var logsSubscription = new TelemetryPipe()
.CollectEventSourceEvents(new[]
{
//new ETWProvider("Microsoft-ServiceFabric-Services"),
//new ETWProvider("Microsoft-ServiceFabric-Actors"),
new ETWProvider("SFActorsPerfTest-SFTestActor")
}, ServiceFabricHelpers.GetEnvironmentProperties(Context))
.SendToElasticSearch(esLogsConfig)
.Start();
using (logsSubscription)
using (metricsSubscription)
{
await base.RunAsync(cancellationToken);
await Task.Delay(Timeout.Infinite, cancellationToken);
}
}
开发者ID:Rurouni,项目名称:MassiveOnlineUniversalServerEngine,代码行数:60,代码来源:Program.cs
示例11: TestRollingEventSequence
static void TestRollingEventSequence(IEnumerable<LogEvent> events, int? retainedFiles, Action<IList<string>> verifyWritten)
{
var fileName = Some.String() + "-{Date}.txt";
var folder = Some.TempFolderPath();
var pathFormat = Path.Combine(folder, fileName);
var log = new LoggerConfiguration()
.WriteTo.SizeRollingFile(pathFormat, retainedFileDurationLimit: TimeSpan.FromSeconds(180))
.CreateLogger();
var verified = new List<string>();
try
{
foreach (var @event in events)
{
log.Write(@event);
var expected = pathFormat.Replace("{Date}", DateTime.UtcNow.ToString("yyyyMMdd") + "_0001");
Assert.True(File.Exists(expected));
verified.Add(expected);
}
}
finally
{
((IDisposable)log).Dispose();
verifyWritten(verified);
Directory.Delete(folder, true);
}
}
开发者ID:Peymanmi,项目名称:Serilog.Sinks.RollingFile.Extension,代码行数:31,代码来源:RollingFileSinkTests.cs
示例12: TestLoggingAndDelete
static void TestLoggingAndDelete(string path)
{
ILogger log = null;
try
{
log = new LoggerConfiguration()
.WriteTo.File(path)
.CreateLogger();
var message = Some.MessageTemplate();
log.Write(new LogEvent(
DateTimeOffset.Now,
LogEventLevel.Information,
null,
message,
Enumerable.Empty<LogEventProperty>()));
var refile = System.IO.File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
var content = new StreamReader(refile).ReadToEnd();
refile.Dispose();
Assert.That(content.Contains(message.Text));
}
finally
{
var disposable = (IDisposable) log;
if (disposable != null) disposable.Dispose();
System.IO.File.Delete(path);
}
}
开发者ID:nicholaspei,项目名称:serilog,代码行数:32,代码来源:FileSinkTests.cs
示例13: CanUseCustomSettingDelimiterToConfigureSettings
public void CanUseCustomSettingDelimiterToConfigureSettings()
{
const string prefix1 = "|";
const string prefix2 = "!";
// Make sure we have the expected keys in the App.config
Assert.AreEqual("Warning", ConfigurationManager.AppSettings["serilog|minimum-level"]);
Assert.AreEqual("Error", ConfigurationManager.AppSettings["serilog!minimum-level"]);
var log1 = new LoggerConfiguration()
.WriteTo.Observers(o => { })
.ReadFrom.AppSettings(null,prefix1)
.CreateLogger();
var log2 = new LoggerConfiguration()
.WriteTo.Observers(o => { })
.ReadFrom.AppSettings(null,prefix2)
.CreateLogger();
Assert.IsFalse(log1.IsEnabled(LogEventLevel.Information));
Assert.IsTrue(log1.IsEnabled(LogEventLevel.Warning));
Assert.IsFalse(log2.IsEnabled(LogEventLevel.Warning));
Assert.IsTrue(log2.IsEnabled(LogEventLevel.Error));
}
开发者ID:Applicita,项目名称:serilog,代码行数:25,代码来源:AppSettingsTests.cs
示例14: WhenALoggerWritesToTheSinkItIsRetrievableFromTheTableWithProperties
public void WhenALoggerWritesToTheSinkItIsRetrievableFromTheTableWithProperties()
{
var storageAccount = CloudStorageAccount.DevelopmentStorageAccount;
var tableClient = storageAccount.CreateCloudTableClient();
var table = tableClient.GetTableReference("LogEventEntity");
table.DeleteIfExists();
var logger = new LoggerConfiguration()
.WriteTo.AzureTableStorageWithProperties(storageAccount)
.CreateLogger();
var exception = new ArgumentException("Some exception");
const string messageTemplate = "{Properties} should go in their {Numbered} {Space}";
logger.Information(exception, messageTemplate, "Properties", 1234, ' ');
var result = table.ExecuteQuery(new TableQuery().Take(1)).First();
// Check the presence of same properties as in previous version
Assert.AreEqual(messageTemplate, result.Properties["MessageTemplate"].StringValue);
Assert.AreEqual("Information", result.Properties["Level"].StringValue);
Assert.AreEqual("System.ArgumentException: Some exception", result.Properties["Exception"].StringValue);
Assert.AreEqual("\"Properties\" should go in their 1234 ", result.Properties["RenderedMessage"].StringValue);
// Check the presence of the new properties.
Assert.AreEqual("Properties", result.Properties["Properties"].PropertyAsObject);
Assert.AreEqual(1234, result.Properties["Numbered"].PropertyAsObject);
Assert.AreEqual(" ", result.Properties["Space"].PropertyAsObject);
}
开发者ID:Sensarg22,项目名称:serilog-sinks-azuretablestorage,代码行数:31,代码来源:AzureTableStorageWithPropertiesSinkTests.cs
示例15: Logger
/// <summary>
/// Write log events to a sub-logger, where further processing may occur. Events through
/// the sub-logger will be constrained by filters and enriched by enrichers that are
/// active in the parent. A sub-logger cannot be used to log at a more verbose level, but
/// a less verbose level is possible.
/// </summary>
/// <param name="configureLogger">An action that configures the sub-logger.</param>
/// <returns>Configuration object allowing method chaining.</returns>
public LoggerConfiguration Logger(
Action<LoggerConfiguration> configureLogger)
{
if (configureLogger == null) throw new ArgumentNullException("configureLogger");
var lc = new LoggerConfiguration();
configureLogger(lc);
return Sink(new CopyingSink((ILogEventSink)lc.CreateLogger()));
}
开发者ID:nicholaspei,项目名称:serilog,代码行数:16,代码来源:LoggerSinkConfiguration.cs
示例16: LoggerTest
public void LoggerTest()
{
var logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.WebRequest(new Uri(Url))
.CreateLogger();
logger.Information("Hello World");
}
开发者ID:WillemRB,项目名称:serilog-sinks-webrequest,代码行数:9,代码来源:WebRequestSinkTests.cs
示例17: LoggerFilterConfiguration
internal LoggerFilterConfiguration(
LoggerConfiguration loggerConfiguration,
Action<ILogEventFilter> addFilter)
{
if (loggerConfiguration == null) throw new ArgumentNullException("loggerConfiguration");
if (addFilter == null) throw new ArgumentNullException("addFilter");
_loggerConfiguration = loggerConfiguration;
_addFilter = addFilter;
}
开发者ID:nicholaspei,项目名称:serilog,代码行数:9,代码来源:LoggerFilterConfiguration.cs
示例18: ShouldCreateInstanceOfLogger
public void ShouldCreateInstanceOfLogger()
{
var loggerConfiguration = new LoggerConfiguration();
loggerConfiguration.WriteTo.SizeRollingFile(new CompactJsonFormatter(), "c:\\logs\\Log-{{Date}}.json", retainedFileDurationLimit: TimeSpan.FromDays(3));
var logger = loggerConfiguration.CreateLogger();
Assert.IsNotNull(logger);
}
开发者ID:Peymanmi,项目名称:Serilog.Sinks.RollingFile.Extension,代码行数:10,代码来源:TestFormatterTest.cs
示例19: GetLogEvent
public static LogEvent GetLogEvent(Action<ILogger> writeAction)
{
LogEvent result = null;
var l = new LoggerConfiguration()
.WriteTo.Sink(new DelegatingSink(le => result = le))
.CreateLogger();
writeAction(l);
return result;
}
开发者ID:DmitryNaumov,项目名称:serilog,代码行数:10,代码来源:DelegatingSink.cs
示例20: LoggerMinimumLevelConfiguration
internal LoggerMinimumLevelConfiguration(LoggerConfiguration loggerConfiguration, Action<LogEventLevel> setMinimum,
Action<LoggingLevelSwitch> setLevelSwitch, Action<string, LoggingLevelSwitch> addOverride)
{
if (loggerConfiguration == null) throw new ArgumentNullException(nameof(loggerConfiguration));
if (setMinimum == null) throw new ArgumentNullException(nameof(setMinimum));
if (addOverride == null) throw new ArgumentNullException(nameof(addOverride));
_loggerConfiguration = loggerConfiguration;
_setMinimum = setMinimum;
_setLevelSwitch = setLevelSwitch;
_addOverride = addOverride;
}
开发者ID:serilog,项目名称:serilog,代码行数:11,代码来源:LoggerMinimumLevelConfiguration.cs
注:本文中的LoggerConfiguration类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论