Skip to content
This repository has been archived by the owner on Dec 13, 2018. It is now read-only.

Commit

Permalink
Add more configuration options for logging, add reload
Browse files Browse the repository at this point in the history
  • Loading branch information
lodejard authored and rynowak committed Oct 29, 2015
1 parent a06e992 commit 9f38745
Show file tree
Hide file tree
Showing 13 changed files with 505 additions and 72 deletions.
84 changes: 78 additions & 6 deletions samples/SampleApp/Program.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
using System;
using System.Collections.Generic;
using Microsoft.AspNet.FileProviders;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
using Microsoft.Extensions.PlatformAbstractions;
using Microsoft.Extensions.Primitives;
using ILogger = Microsoft.Extensions.Logging.ILogger;

namespace SampleApp
Expand All @@ -21,14 +27,72 @@ public Program()
factory.AddNLog(new global::NLog.LogFactory());
factory.AddEventLog();
#endif
factory.AddConsole(includeScopes: true);

// How to configure the console logger to reload based on a configuration file.
//
//
var loggingConfiguration = new ConfigurationBuilder().AddJsonFile("logging.json").Build();
factory.AddConsole(loggingConfiguration);
loggingConfiguration.ReloadOnChanged("logging.json");

// How to configure the console logger to use settings provided in code.
//
//
//var settings = new ConsoleLoggerSettings()
//{
// IncludeScopes = true,
// Switches =
// {
// ["Default"] = LogLevel.Verbose,
// ["Microsoft"] = LogLevel.Information,
// }
//};
//factory.AddConsole(settings);

// How to manually wire up file-watching without a configuration file
//
//
//factory.AddConsole(new RandomReloadingConsoleSettings());
}

private class RandomReloadingConsoleSettings : IConsoleLoggerSettings
{
private PhysicalFileProvider _files = new PhysicalFileProvider(PlatformServices.Default.Application.ApplicationBasePath);

public RandomReloadingConsoleSettings()
{
Reload();
}

public IChangeToken ChangeToken { get; private set; }

public bool IncludeScopes { get; }

private Dictionary<string, LogLevel> Switches { get; set; }

public IConsoleLoggerSettings Reload()
{
ChangeToken = _files.Watch("logging.json");
Switches = new Dictionary<string, LogLevel>()
{
["Default"] = (LogLevel)(DateTimeOffset.Now.Second % 5 + 1),
["Microsoft"] = (LogLevel)(DateTimeOffset.Now.Second % 5 + 1),
};

return this;
}

public bool TryGetSwitch(string name, out LogLevel level)
{
return Switches.TryGetValue(name, out level);
}
}

public void Main(string[] args)
{
_logger.LogInformation("Starting");

var startTime = DateTimeOffset.UtcNow;
var startTime = DateTimeOffset.Now;
_logger.LogInformation(1, "Started at '{StartTime}' and 0x{Hello:X} is hex of 42", startTime, 42);
// or
_logger.ProgramStarting(startTime, 42);
Expand All @@ -48,15 +112,23 @@ public void Main(string[] args)

using (_logger.BeginScopeImpl("Main"))
{
Console.WriteLine("Hello World");

_logger.LogInformation("Waiting for user input");
var input = Console.ReadLine();
_logger.LogInformation("User typed '{input}' on the command line", input);

string input;
do
{
Console.WriteLine("Enter some test to log more, or 'quit' to exit.");
input = Console.ReadLine();

_logger.LogInformation("User typed '{input}' on the command line", input);
_logger.LogWarning("The time is now {Time}, it's getting late!", DateTimeOffset.Now);
}
while (input != "quit");
}
}

var endTime = DateTimeOffset.UtcNow;
var endTime = DateTimeOffset.Now;
_logger.LogInformation(2, "Stopping at '{StopTime}'", endTime);
// or
_logger.ProgramStopping(endTime);
Expand Down
8 changes: 8 additions & 0 deletions samples/SampleApp/logging.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"includeScopes" : "false",
"switches": {
"Default": "Verbose",
"System": "Information",
"Microsoft": "Information"
}
}
40 changes: 22 additions & 18 deletions samples/SampleApp/project.json
Original file line number Diff line number Diff line change
@@ -1,22 +1,26 @@
{
"commands": {
"SampleApp": "SampleApp"
"commands": {
"SampleApp": "SampleApp"
},
"dependencies": {
"Microsoft.AspNet.FileProviders.Physical": "1.0.0-*",
"Microsoft.Extensions.Configuration.FileProviderExtensions": "1.0.0-*",
"Microsoft.Extensions.Configuration.Json": "1.0.0-*",
"Microsoft.Extensions.Logging": "1.0.0-*",
"Microsoft.Extensions.Logging.Console": "1.0.0-*",
"Microsoft.Extensions.PlatformAbstractions": "1.0.0-*"
},
"frameworks": {
"dnx451": {
"dependencies": {
"Microsoft.Extensions.Logging.EventLog": "1.0.0-*",
"Microsoft.Extensions.Logging.NLog": "1.0.0-*"
}
},
"dependencies": {
"Microsoft.Extensions.Logging": "1.0.0-*",
"Microsoft.Extensions.Logging.Console": "1.0.0-*"
},
"frameworks": {
"dnx451": {
"dependencies": {
"Microsoft.Extensions.Logging.EventLog": "1.0.0-*",
"Microsoft.Extensions.Logging.NLog": "1.0.0-*"
}
},
"dnxcore50": {
"dependencies": {
"System.Console": "4.0.0-beta-*"
}
}
"dnxcore50": {
"dependencies": {
"System.Console": "4.0.0-beta-*"
}
}
}
}
5 changes: 5 additions & 0 deletions src/Microsoft.Extensions.Logging.Abstractions/LogLevel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,5 +42,10 @@ public enum LogLevel
/// immediate attention.
/// </summary>
Critical = 6,

/// <summary>
/// Not used for writing log messages. Specifies that a logging category should not write any messages.
/// </summary>
None = int.MaxValue,
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Primitives;

namespace Microsoft.Extensions.Logging.Console
{
public class ConfigurationConsoleLoggerSettings : IConsoleLoggerSettings
{
private readonly IConfiguration _configuration;

public ConfigurationConsoleLoggerSettings(IConfiguration configuration)
{
_configuration = configuration;
ChangeToken = configuration.GetReloadToken();
}

public IChangeToken ChangeToken { get; private set; }

public bool IncludeScopes
{
get
{
bool includeScopes;
var value = _configuration["includeScopes"];
if (string.IsNullOrEmpty(value))
{
return false;
}
else if (bool.TryParse(value, out includeScopes))
{
return includeScopes;
}
else
{
var message = $"Configuration value '{value}' for setting '{nameof(IncludeScopes)}' is not supported.";
throw new InvalidOperationException(message);
}
}
}

public IConsoleLoggerSettings Reload()
{
ChangeToken = null;
return new ConfigurationConsoleLoggerSettings(_configuration);
}

public bool TryGetSwitch(string name, out LogLevel level)
{
var switches = _configuration.GetSection("switches");
if (switches == null)
{
level = LogLevel.None;
return false;
}

var value = switches[name];
if (string.IsNullOrEmpty(value))
{
level = LogLevel.None;
return false;
}
else if (Enum.TryParse<LogLevel>(value, out level))
{
return true;
}
else
{
var message = $"Configuration value '{value}' for category '{name}' is not supported.";
throw new InvalidOperationException(message);
}
}
}
}
57 changes: 45 additions & 12 deletions src/Microsoft.Extensions.Logging.Console/ConsoleLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ public class ConsoleLogger : ILogger
private readonly ConsoleColor? DefaultConsoleColor = null;

private const int _indentation = 2;
private readonly string _name;
private readonly Func<string, LogLevel, bool> _filter;
private readonly bool _includeScopes;

private IConsole _console;
private Func<string, LogLevel, bool> _filter;

static ConsoleLogger()
{
Expand All @@ -33,9 +33,14 @@ static ConsoleLogger()

public ConsoleLogger(string name, Func<string, LogLevel, bool> filter, bool includeScopes)
{
_name = name;
_filter = filter ?? ((category, logLevel) => true);
_includeScopes = includeScopes;
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}

Name = name;
Filter = filter ?? ((category, logLevel) => true);
IncludeScopes = includeScopes;

if (RuntimeEnvironmentHelper.IsWindows)
{
Expand All @@ -47,9 +52,37 @@ public ConsoleLogger(string name, Func<string, LogLevel, bool> filter, bool incl
}
}

public IConsole Console { get; set; }
public IConsole Console
{
get { return _console; }
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}

_console = value;
}
}

public Func<string, LogLevel, bool> Filter
{
get { return _filter; }
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}

_filter = value;
}
}

public bool IncludeScopes { get; set; }

protected string Name { get { return _name; } }
public string Name { get; }

public void Log(LogLevel logLevel, int eventId, object state, Exception exception, Func<object, Exception, string> formatter)
{
Expand Down Expand Up @@ -86,7 +119,7 @@ public void Log(LogLevel logLevel, int eventId, object state, Exception exceptio
return;
}

WriteMessage(logLevel, _name, eventId, message);
WriteMessage(logLevel, Name, eventId, message);
}

public virtual void WriteMessage(LogLevel logLevel, string logName, int eventId, string message)
Expand Down Expand Up @@ -118,7 +151,7 @@ public virtual void WriteMessage(LogLevel logLevel, string logName, int eventId,
newLine: true);

// scope information
if (_includeScopes)
if (IncludeScopes)
{
var scopeInformation = GetScopeInformation();
if (!string.IsNullOrEmpty(scopeInformation))
Expand Down Expand Up @@ -146,7 +179,7 @@ public virtual void WriteMessage(LogLevel logLevel, string logName, int eventId,

public bool IsEnabled(LogLevel logLevel)
{
return _filter(_name, logLevel);
return Filter(Name, logLevel);
}

public IDisposable BeginScopeImpl(object state)
Expand All @@ -156,7 +189,7 @@ public IDisposable BeginScopeImpl(object state)
throw new ArgumentNullException(nameof(state));
}

return ConsoleLogScope.Push(_name, state);
return ConsoleLogScope.Push(Name, state);
}

private void FormatLogValues(StringBuilder builder, ILogValues logValues, int level, bool bullet)
Expand Down
Loading

0 comments on commit 9f38745

Please sign in to comment.