Skip to content

Commit 66f015a

Browse files
committed
modify BatchHost, write Readme fully
1 parent 00e1cd1 commit 66f015a

File tree

9 files changed

+436
-156
lines changed

9 files changed

+436
-156
lines changed

ReadMe.md

Lines changed: 334 additions & 80 deletions
Large diffs are not rendered by default.

sandbox/MultiContainedApp/Program.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using MicroBatchFramework;
22
using Microsoft.Extensions.Hosting;
33
using Microsoft.Extensions.Logging;
4+
using System;
45
using System.Threading.Tasks;
56

67
namespace MultiContainedApp

sandbox/SingleContainedApp/Program.cs

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
11
using MicroBatchFramework;
2+
using MicroBatchFramework.Logging;
3+
using Microsoft.Extensions.Configuration;
4+
using Microsoft.Extensions.DependencyInjection;
25
using Microsoft.Extensions.Hosting;
36
using Microsoft.Extensions.Logging;
7+
using Microsoft.Extensions.Options;
48
using System;
9+
using System.IO;
510
using System.Reflection;
611
using System.Text;
712
using System.Threading.Tasks;
@@ -20,6 +25,34 @@ public void Hello(
2025
}
2126
}
2227

28+
IOptions<MyConfig> config;
29+
ILogger<MyFirstBatch> logger;
30+
31+
public MyFirstBatch(IOptions<MyConfig> config, ILogger<MyFirstBatch> logger)
32+
{
33+
this.config = config;
34+
this.logger = logger;
35+
}
36+
37+
[Command("log")]
38+
public void LogWrite()
39+
{
40+
Context.Logger.LogTrace("t r a c e");
41+
Context.Logger.LogDebug("d e b u g");
42+
Context.Logger.LogInformation("i n f o");
43+
Context.Logger.LogCritical("c r i t i c a l");
44+
Context.Logger.LogWarning("w a r n");
45+
Context.Logger.LogError("e r r o r");
46+
}
47+
48+
[Command("opt")]
49+
public void ShowOption()
50+
{
51+
Console.WriteLine(config.Value.Bar);
52+
Console.WriteLine(config.Value.Foo);
53+
}
54+
55+
2356
[Command("version", "yeah, go!")]
2457
public void ShowVersion()
2558
{
@@ -48,6 +81,12 @@ public async Task Timer([Option(0)]uint waitSeconds)
4881
}
4982
}
5083

84+
public class MyConfig
85+
{
86+
public int Foo { get; set; }
87+
public bool Bar { get; set; }
88+
}
89+
5190
public class OverrideCheck : BatchBase
5291
{
5392
[Command("encode", "encode input string to base64url")]
@@ -77,7 +116,13 @@ class Program
77116
{
78117
static async Task Main(string[] args)
79118
{
80-
await new HostBuilder().RunBatchEngineAsync<OverrideCheck>(args);
119+
await BatchHost.CreateDefaultBuilder()
120+
.ConfigureServices((hostContext, services) =>
121+
{
122+
// mapping config json to IOption<MyConfig>
123+
services.Configure<MyConfig>(hostContext.Configuration);
124+
})
125+
.RunBatchEngineAsync<MyFirstBatch>(args);
81126
}
82127
}
83128
}

sandbox/SingleContainedApp/SingleContainedApp.csproj

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,21 @@
1-
<Project Sdk="Microsoft.NET.Sdk">
1+
<Project Sdk="Microsoft.NET.Sdk">
22

33
<PropertyGroup>
44
<OutputType>Exe</OutputType>
55
<TargetFramework>netcoreapp2.1</TargetFramework>
66
<LangVersion>7.3</LangVersion>
77
</PropertyGroup>
88

9+
<ItemGroup>
10+
<None Remove="appsettings.json" />
11+
</ItemGroup>
12+
13+
<ItemGroup>
14+
<Content Include="appsettings.json">
15+
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
16+
</Content>
17+
</ItemGroup>
18+
919
<ItemGroup>
1020
<PackageReference Include="Microsoft.Extensions.Configuration.CommandLine" Version="2.2.0" />
1121
<PackageReference Include="Microsoft.Extensions.Hosting" Version="2.2.0" />
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
{
2+
"Foo": 42,
3+
"Bar": true
4+
}

sandbox/SingleContainedAppWithConfig/Program.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
using MicroBatchFramework;
2-
using MicroBatchFramework.Configuration;
32
using Microsoft.Extensions.DependencyInjection;
43
using Microsoft.Extensions.Logging;
54
using Microsoft.Extensions.Options;
@@ -34,7 +33,7 @@ class Program
3433
static async Task Main(string[] args)
3534
{
3635
// using MicroBatchFramework.Configuration;
37-
await MicroBatchHost.CreateDefaultBuilder(args, LogLevel.Debug)
36+
await MicroBatchFramework.BatchHost.CreateDefaultBuilder()
3837
.ConfigureServices((hostContext, services) =>
3938
{
4039
services.AddOptions();
Lines changed: 35 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,19 @@
11
using MicroBatchFramework.Logging;
2+
using Microsoft.Extensions.DependencyInjection;
23
using Microsoft.Extensions.Configuration;
34
using Microsoft.Extensions.Hosting;
45
using Microsoft.Extensions.Logging;
56
using System;
67
using System.IO;
78
using System.Reflection;
89

9-
namespace MicroBatchFramework.Configuration
10+
namespace MicroBatchFramework
1011
{
1112
// ref: https://github.com/aspnet/AspNetCore/blob/4e44025a52e4b73aa17e09a8041b0e166e0c5ce0/src/DefaultBuilder/src/WebHost.cs
1213
/// <summary>
1314
/// Provides convenience methods for creating instances of <see cref="IHost"/> and <see cref="IHostBuilder"/> with pre-configured defaults.
1415
/// </summary>
15-
public static class MicroBatchHost
16+
public static class BatchHost
1617
{
1718
/// <summary>
1819
/// Initializes a new instance of the <see cref="HostBuilder"/> class with pre-configured defaults.
@@ -26,8 +27,7 @@ public static class MicroBatchHost
2627
/// and configure the <see cref="SimpleConsoleLogger"/> to log to the console,
2728
/// </remarks>
2829
/// <returns>The initialized <see cref="IHostBuilder"/>.</returns>
29-
public static IHostBuilder CreateDefaultBuilder() =>
30-
CreateDefaultBuilder(args: null);
30+
public static IHostBuilder CreateDefaultBuilder(bool useSimpleConosoleLogger = true) => CreateDefaultBuilder(useSimpleConosoleLogger, LogLevel.Debug);
3131

3232
/// <summary>
3333
/// Initializes a new instance of the <see cref="HostBuilder"/> class with pre-configured defaults.
@@ -38,31 +38,12 @@ public static IHostBuilder CreateDefaultBuilder() =>
3838
/// load <see cref="IConfiguration"/> from 'appsettings.json' and 'appsettings.[<see cref="IHostingEnvironment.EnvironmentName"/>].json',
3939
/// load <see cref="IConfiguration"/> from User Secrets when <see cref="IHostingEnvironment.EnvironmentName"/> is 'Development' using the entry assembly,
4040
/// load <see cref="IConfiguration"/> from environment variables,
41-
/// load <see cref="IConfiguration"/> from supplied command line args,
4241
/// and configure the <see cref="SimpleConsoleLogger"/> to log to the console,
4342
/// </remarks>
44-
/// <param name="args"></param>
43+
/// <param name="useSimpleConosoleLogger"></param>
44+
/// <param name="minSimpleConsoleLoggerLogLevel"></param>
4545
/// <returns>The initialized <see cref="IHostBuilder"/>.</returns>
46-
public static IHostBuilder CreateDefaultBuilder(string[] args) =>
47-
CreateDefaultBuilder(args, new SimpleConsoleLoggerOption().MinLogLevel);
48-
49-
/// <summary>
50-
/// Initializes a new instance of the <see cref="HostBuilder"/> class with pre-configured defaults.
51-
/// </summary>
52-
/// <remarks>
53-
/// The following defaults are applied to the returned <see cref="HostBuilder"/>:
54-
/// set the <see cref="IHostingEnvironment.EnvironmentName"/> to the NETCORE_ENVIRONMENT,
55-
/// load <see cref="IConfiguration"/> from 'appsettings.json' and 'appsettings.[<see cref="IHostingEnvironment.EnvironmentName"/>].json',
56-
/// load <see cref="IConfiguration"/> from User Secrets when <see cref="IHostingEnvironment.EnvironmentName"/> is 'Development' using the entry assembly,
57-
/// load <see cref="IConfiguration"/> from environment variables,
58-
/// load <see cref="IConfiguration"/> from supplied command line args,
59-
/// and configure the <see cref="SimpleConsoleLogger"/> to log to the console,
60-
/// </remarks>
61-
/// <param name="args"></param>
62-
/// <param name="minLogLevel"></param>
63-
/// <returns>The initialized <see cref="IHostBuilder"/>.</returns>
64-
public static IHostBuilder CreateDefaultBuilder(string[] args, LogLevel minLogLevel) =>
65-
CreateDefaultBuilder(args, minLogLevel, "");
46+
public static IHostBuilder CreateDefaultBuilder(bool useSimpleConosoleLogger, LogLevel minSimpleConsoleLoggerLogLevel) => CreateDefaultBuilder(useSimpleConosoleLogger, minSimpleConsoleLoggerLogLevel, "");
6647

6748
/// <summary>
6849
/// Initializes a new instance of the <see cref="HostBuilder"/> class with pre-configured defaults.
@@ -73,43 +54,34 @@ public static IHostBuilder CreateDefaultBuilder(string[] args, LogLevel minLogLe
7354
/// load <see cref="IConfiguration"/> from 'appsettings.json' and 'appsettings.[<see cref="IHostingEnvironment.EnvironmentName"/>].json',
7455
/// load <see cref="IConfiguration"/> from User Secrets when <see cref="IHostingEnvironment.EnvironmentName"/> is 'Development' using the entry assembly,
7556
/// load <see cref="IConfiguration"/> from environment variables,
76-
/// load <see cref="IConfiguration"/> from supplied command line args,
7757
/// and configure the <see cref="SimpleConsoleLogger"/> to log to the console,
7858
/// </remarks>
79-
/// <param name="args"></param>
80-
/// <param name="minLogLevel"></param>
59+
/// <param name="useSimpleConosoleLogger"></param>
60+
/// <param name="minSimpleConsoleLoggerLogLevel"></param>
8161
/// <param name="hostEnvironmentVariable"></param>
8262
/// <returns>The initialized <see cref="IHostBuilder"/>.</returns>
83-
public static IHostBuilder CreateDefaultBuilder(string[] args, LogLevel minLogLevel, string hostEnvironmentVariable)
63+
public static IHostBuilder CreateDefaultBuilder(bool useSimpleConosoleLogger, LogLevel minSimpleConsoleLoggerLogLevel, string hostEnvironmentVariable)
8464
{
8565
var builder = new HostBuilder();
8666

8767
builder.UseContentRoot(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
88-
ConfigureContextDefault(builder, hostEnvironmentVariable);
89-
ConfigureConfigDefault(builder, args);
90-
ConfigureLoggingDefault(builder, minLogLevel);
68+
ConfigureAppConfigurationDefault(builder, hostEnvironmentVariable);
69+
ConfigureLoggingDefault(builder, useSimpleConosoleLogger, minSimpleConsoleLoggerLogLevel);
70+
9171
return builder;
9272
}
9373

94-
internal static void ConfigureContextDefault(IHostBuilder builder, string contextEnvironmentVariable)
74+
internal static void ConfigureAppConfigurationDefault(IHostBuilder builder, string hostEnvironmentVariable)
9575
{
9676
builder.ConfigureAppConfiguration((hostingContext, config) =>
9777
{
9878
var env = hostingContext.HostingEnvironment;
9979
env.ApplicationName = Assembly.GetExecutingAssembly().GetName().Name;
100-
if (string.IsNullOrWhiteSpace(contextEnvironmentVariable))
80+
if (string.IsNullOrWhiteSpace(hostEnvironmentVariable))
10181
{
102-
contextEnvironmentVariable = "NETCORE_ENVIRONMENT";
82+
hostEnvironmentVariable = "NETCORE_ENVIRONMENT";
10383
}
104-
env.EnvironmentName = System.Environment.GetEnvironmentVariable(contextEnvironmentVariable) ?? "Production";
105-
});
106-
}
107-
108-
internal static void ConfigureConfigDefault(IHostBuilder builder, string[] args)
109-
{
110-
builder.ConfigureAppConfiguration((hostingContext, config) =>
111-
{
112-
var env = hostingContext.HostingEnvironment;
84+
env.EnvironmentName = System.Environment.GetEnvironmentVariable(hostEnvironmentVariable) ?? "Production";
11385

11486
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
11587
config.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
@@ -125,22 +97,28 @@ internal static void ConfigureConfigDefault(IHostBuilder builder, string[] args)
12597
}
12698

12799
config.AddEnvironmentVariables();
128-
129-
if (args != null)
130-
{
131-
config.AddCommandLine(args);
132-
}
133100
});
134101
}
135102

136-
internal static void ConfigureLoggingDefault(IHostBuilder builder, LogLevel minLogLevel)
103+
internal static void ConfigureLoggingDefault(IHostBuilder builder, bool useSimpleConosoleLogger, LogLevel minSimpleConsoleLoggerLogLevel)
137104
{
138-
builder.ConfigureLogging(logging =>
105+
if (useSimpleConosoleLogger)
139106
{
140-
logging.AddSimpleConsole();
141-
// Set ILogger<MicroBatchFramework.BatchEngine> Minimum log level filter.
142-
logging.AddFilter<SimpleConsoleLoggerProvider>("MicroBatchFramework.BatchEngine", minLogLevel);
143-
});
107+
builder.ConfigureLogging(logging =>
108+
{
109+
logging.AddSimpleConsole();
110+
logging.AddFilter<SimpleConsoleLoggerProvider>((category, level) =>
111+
{
112+
// omit system message
113+
if (category.StartsWith("Microsoft.Extensions.Hosting.Internal"))
114+
{
115+
if (level <= LogLevel.Debug) return false;
116+
}
117+
118+
return level >= minSimpleConsoleLoggerLogLevel;
119+
});
120+
});
121+
}
144122
}
145123
}
146-
}
124+
}

src/MicroBatchFramework/MicroBatchFramework.csproj

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,6 @@
2626
</PropertyGroup>
2727

2828
<ItemGroup>
29-
<PackageReference Include="Microsoft.Extensions.Configuration.CommandLine" Version="2.2.0" />
3029
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="2.2.0" />
3130
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.2.0" />
3231
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="2.2.0" />

src/MicroBatchFramework/SimpleConsoleLogger.cs

Lines changed: 4 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,9 @@ public class SimpleConsoleLoggerProvider : ILoggerProvider
1010
{
1111
readonly SimpleConsoleLogger logger;
1212

13-
public SimpleConsoleLoggerProvider(IOptions<SimpleConsoleLoggerOption> option)
13+
public SimpleConsoleLoggerProvider()
1414
{
15-
logger = new SimpleConsoleLogger(option.Value.MinLogLevel);
15+
logger = new SimpleConsoleLogger();
1616
}
1717

1818
public ILogger CreateLogger(string categoryName)
@@ -27,11 +27,8 @@ public void Dispose()
2727

2828
public class SimpleConsoleLogger : ILogger
2929
{
30-
readonly LogLevel minLogLevel;
31-
32-
public SimpleConsoleLogger(LogLevel minLogLevel)
30+
public SimpleConsoleLogger()
3331
{
34-
this.minLogLevel = minLogLevel;
3532
}
3633

3734
public IDisposable BeginScope<TState>(TState state)
@@ -41,13 +38,11 @@ public IDisposable BeginScope<TState>(TState state)
4138

4239
public bool IsEnabled(LogLevel logLevel)
4340
{
44-
if (logLevel == LogLevel.None) return false;
45-
return (int)logLevel >= (int)this.minLogLevel;
41+
return true;
4642
}
4743

4844
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
4945
{
50-
if (!IsEnabled(logLevel)) return;
5146
if (formatter == null) throw new ArgumentNullException(nameof(formatter));
5247

5348
var msg = formatter(state, exception);
@@ -74,11 +69,6 @@ public void Dispose()
7469
}
7570
}
7671

77-
public class SimpleConsoleLoggerOption
78-
{
79-
public LogLevel MinLogLevel { get; set; } = LogLevel.Trace; // default is trace(should use another filter).
80-
}
81-
8272
public static class SimpleConsoleLoggerExtensions
8373
{
8474
public static ILoggingBuilder AddSimpleConsole(this ILoggingBuilder builder)

0 commit comments

Comments
 (0)