我在.net core 3.1中有这个项目。我已配置为使用 SeriLog 作为记录器。
其中一项服务MqttComunicationClient
是将记录器注入使用 serilog 配置的构造函数。这里ILogger
是Microsoft.Extensions.Logging
public MqttCommunicationClient(
IMqttCommunicationConfiguration mqttConfiguration,
ILogger logger,
)
{
this.mqttConfiguration = mqttConfiguration;
this.logger = logger;
}
通过这个类的Init
方法,我正在初始化自定义编写的 MQTT API。
public void Initialize()
{
var mqttClientId = $"{DefaultClientIdPattern}{Environment.MachineName}";
serviceHost = Host.CreateDefaultBuilder()
.UseMQTTApi(opt =>
{
opt.UserName = "test";
opt.Password = "test";
})
.ConfigureServices(services =>
{
services.AddSingleton(logger);
})
.ConfigureHostConfiguration(c => { c.Build(); })
.Start();
managedMqttClient = serviceHost.Services.GetRequiredService<IManagedMqttClient>();
}
我的 MQTT Api 有处理程序,这些处理程序将在收到指定主题的消息时触发。
其中一个处理程序具有以下构造函数。
public ConnectionStatusHandler(
ILogger<ConnectionStatus> logger,
IDeviceCommunications deviceCommunications)
{
this.logger = logger;
this.deviceCommunications = deviceCommunications;
}
现在的问题是当我调试我MqttComunicationClient
的记录器配置为SeriLog
. 根据logger.LogInformation()
此类内部使用的要求和配置,正在记录到日志文件。
当ConnectionStatusHandler
被称为对Logger的logger
更改时。Microsoft.Extensions.Logging.Logger
类中使用的记录器ConnectionStatusHandler
仅记录到控制台而不是文件中。
如何将相同的 serilog 配置logger
对象MqttComunicationClient
传递给ConnectionStatusHandler
? 我需要一些额外的设置吗?我是一个新手,所以任何帮助表示赞赏。
编辑
配置serilog
为记录器的代码
public IServiceProvider CreateServiceProvider(string basePath)
{
var configuration = GetConfiguration(basePath);
var logger = CreateLogger(configuration);
var services = new ServiceCollection();
services.AddSingleton(logger);
return services.BuildServiceProvider();
}
protected virtual ILogger CreateLogger(IConfiguration configuration)
{
return LogBuilder.CreateLogger(null, configuration);
}
// Serilog configured here
public static ILogger CreateLogger(string categoryName, IConfiguration configuration, Action<string> selfLogAction = null)
{
var serilogLogger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
using (var serilogLoggerProvider = new SerilogLoggerProvider(serilogLogger))
{
var logger = serilogLoggerProvider.CreateLogger(categoryName);
if (selfLogAction != null)
{
Serilog.Debugging.SelfLog.Enable(selfLogAction);
}
return logger;
}
}
// This method reads the configuration from the config json file.
protected virtual IConfiguration GetConfiguration(string basePath)
{
StringBuilder configLog = null;
var mainConfiguration = new ConfigurationBuilder()
.SetBasePath(basePath)
.AddJsonFile("mytest.config.json")
.Build();
var builder = new ConfigurationBuilder();
return BuildConfiguration(builder, mainConfiguration, basePath, configLog)
.Build();
}