création du DSLink RSTP/FFMPEG

This commit is contained in:
FARINA Louis 2021-07-13 15:13:42 +02:00
parent 5646904956
commit 01448676f7
92 changed files with 6347 additions and 323 deletions

Binary file not shown.

View file

@ -1,7 +0,0 @@
{
"ExpandedNodes": [
"",
"\\DSLink_Test"
],
"PreviewInSolutionExplorer": false
}

Binary file not shown.

View file

@ -1,7 +0,0 @@
{
"ExpandedNodes": [
""
],
"SelectedNode": "\\CMakeLists.txt",
"PreviewInSolutionExplorer": false
}

View file

@ -1,15 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<Configurations>Debug;Release</Configurations>
</PropertyGroup>
<ItemGroup>
<Reference Include="DSLink">
<HintPath>DSLink.dll</HintPath>
</Reference>
</ItemGroup>
</Project>

View file

@ -1,16 +0,0 @@
using System;
using DSLink;
class ExampleDSLink : DSLinkContainer
{
public ExampleDSLink() : base(new Configuration("example", responder: true))
{
Console.WriteLine("Starting DSLink...");
}
private static void Main()
{
new ExampleDSLink();
Console.ReadLine(); // Keep the link running.
}
}

View file

@ -1,39 +0,0 @@
{
"runtimeTarget": {
"name": ".NETCoreApp,Version=v3.1",
"signature": ""
},
"compilationOptions": {},
"targets": {
".NETCoreApp,Version=v3.1": {
"DSLink_Test/1.0.0": {
"dependencies": {
"DSLink": "1.0.0.0"
},
"runtime": {
"DSLink_Test.dll": {}
}
},
"DSLink/1.0.0.0": {
"runtime": {
"DSLink.dll": {
"assemblyVersion": "1.0.0.0",
"fileVersion": "1.0.0.0"
}
}
}
}
},
"libraries": {
"DSLink_Test/1.0.0": {
"type": "project",
"serviceable": false,
"sha512": ""
},
"DSLink/1.0.0.0": {
"type": "reference",
"serviceable": false,
"sha512": ""
}
}
}

View file

@ -1,62 +0,0 @@
{
"format": 1,
"restore": {
"C:\\Users\\l.farina\\Desktop\\UCRM_stage\\DSLink_Test\\DSLink_Test\\DSLink_Test.csproj": {}
},
"projects": {
"C:\\Users\\l.farina\\Desktop\\UCRM_stage\\DSLink_Test\\DSLink_Test\\DSLink_Test.csproj": {
"version": "1.0.0",
"restore": {
"projectUniqueName": "C:\\Users\\l.farina\\Desktop\\UCRM_stage\\DSLink_Test\\DSLink_Test\\DSLink_Test.csproj",
"projectName": "DSLink_Test",
"projectPath": "C:\\Users\\l.farina\\Desktop\\UCRM_stage\\DSLink_Test\\DSLink_Test\\DSLink_Test.csproj",
"packagesPath": "C:\\Users\\l.farina\\.nuget\\packages\\",
"outputPath": "C:\\Users\\l.farina\\Desktop\\UCRM_stage\\DSLink_Test\\DSLink_Test\\obj\\",
"projectStyle": "PackageReference",
"configFilePaths": [
"C:\\Users\\l.farina\\AppData\\Roaming\\NuGet\\NuGet.Config",
"C:\\Program Files (x86)\\NuGet\\Config\\Microsoft.VisualStudio.Offline.config"
],
"originalTargetFrameworks": [
"netcoreapp3.1"
],
"sources": {
"C:\\Program Files (x86)\\Microsoft SDKs\\NuGetPackages\\": {},
"https://api.nuget.org/v3/index.json": {}
},
"frameworks": {
"netcoreapp3.1": {
"targetAlias": "netcoreapp3.1",
"projectReferences": {}
}
},
"warningProperties": {
"warnAsError": [
"NU1605"
]
}
},
"frameworks": {
"netcoreapp3.1": {
"targetAlias": "netcoreapp3.1",
"imports": [
"net461",
"net462",
"net47",
"net471",
"net472",
"net48"
],
"assetTargetFallback": true,
"warn": true,
"frameworkReferences": {
"Microsoft.NETCore.App": {
"privateAssets": "all"
}
},
"runtimeIdentifierGraphPath": "C:\\Program Files\\dotnet\\sdk\\5.0.301\\RuntimeIdentifierGraph.json"
}
}
}
}
}

View file

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects>
</PropertyGroup>
</Project>

View file

@ -1 +0,0 @@
04e11fc9f114ddb9939a4a129dda1f1f0f8cc542

View file

@ -1 +0,0 @@
7ce18094f6e3334762ad9383b8e4e114e700dd30

View file

@ -1,28 +0,0 @@
C:\Users\l.farina\source\repos\DSLink_Test\DSLink_Test\bin\Debug\netcoreapp3.1\DSLink_Test.exe
C:\Users\l.farina\source\repos\DSLink_Test\DSLink_Test\bin\Debug\netcoreapp3.1\DSLink_Test.deps.json
C:\Users\l.farina\source\repos\DSLink_Test\DSLink_Test\bin\Debug\netcoreapp3.1\DSLink_Test.runtimeconfig.json
C:\Users\l.farina\source\repos\DSLink_Test\DSLink_Test\bin\Debug\netcoreapp3.1\DSLink_Test.runtimeconfig.dev.json
C:\Users\l.farina\source\repos\DSLink_Test\DSLink_Test\bin\Debug\netcoreapp3.1\DSLink_Test.dll
C:\Users\l.farina\source\repos\DSLink_Test\DSLink_Test\bin\Debug\netcoreapp3.1\DSLink_Test.pdb
C:\Users\l.farina\source\repos\DSLink_Test\DSLink_Test\obj\Debug\netcoreapp3.1\DSLink_Test.csproj.AssemblyReference.cache
C:\Users\l.farina\source\repos\DSLink_Test\DSLink_Test\obj\Debug\netcoreapp3.1\DSLink_Test.AssemblyInfoInputs.cache
C:\Users\l.farina\source\repos\DSLink_Test\DSLink_Test\obj\Debug\netcoreapp3.1\DSLink_Test.AssemblyInfo.cs
C:\Users\l.farina\source\repos\DSLink_Test\DSLink_Test\obj\Debug\netcoreapp3.1\DSLink_Test.csproj.CoreCompileInputs.cache
C:\Users\l.farina\source\repos\DSLink_Test\DSLink_Test\obj\Debug\netcoreapp3.1\DSLink_Test.dll
C:\Users\l.farina\source\repos\DSLink_Test\DSLink_Test\obj\Debug\netcoreapp3.1\DSLink_Test.pdb
C:\Users\l.farina\source\repos\DSLink_Test\DSLink_Test\obj\Debug\netcoreapp3.1\DSLink_Test.genruntimeconfig.cache
C:\Users\l.farina\Desktop\UCRM_stage\DSLink_Test\DSLink_Test\bin\Debug\netcoreapp3.1\DSLink_Test.exe
C:\Users\l.farina\Desktop\UCRM_stage\DSLink_Test\DSLink_Test\bin\Debug\netcoreapp3.1\DSLink_Test.deps.json
C:\Users\l.farina\Desktop\UCRM_stage\DSLink_Test\DSLink_Test\bin\Debug\netcoreapp3.1\DSLink_Test.runtimeconfig.json
C:\Users\l.farina\Desktop\UCRM_stage\DSLink_Test\DSLink_Test\bin\Debug\netcoreapp3.1\DSLink_Test.runtimeconfig.dev.json
C:\Users\l.farina\Desktop\UCRM_stage\DSLink_Test\DSLink_Test\bin\Debug\netcoreapp3.1\DSLink_Test.dll
C:\Users\l.farina\Desktop\UCRM_stage\DSLink_Test\DSLink_Test\bin\Debug\netcoreapp3.1\DSLink_Test.pdb
C:\Users\l.farina\Desktop\UCRM_stage\DSLink_Test\DSLink_Test\obj\Debug\netcoreapp3.1\DSLink_Test.csproj.AssemblyReference.cache
C:\Users\l.farina\Desktop\UCRM_stage\DSLink_Test\DSLink_Test\obj\Debug\netcoreapp3.1\DSLink_Test.AssemblyInfoInputs.cache
C:\Users\l.farina\Desktop\UCRM_stage\DSLink_Test\DSLink_Test\obj\Debug\netcoreapp3.1\DSLink_Test.AssemblyInfo.cs
C:\Users\l.farina\Desktop\UCRM_stage\DSLink_Test\DSLink_Test\obj\Debug\netcoreapp3.1\DSLink_Test.csproj.CoreCompileInputs.cache
C:\Users\l.farina\Desktop\UCRM_stage\DSLink_Test\DSLink_Test\obj\Debug\netcoreapp3.1\DSLink_Test.dll
C:\Users\l.farina\Desktop\UCRM_stage\DSLink_Test\DSLink_Test\obj\Debug\netcoreapp3.1\DSLink_Test.pdb
C:\Users\l.farina\Desktop\UCRM_stage\DSLink_Test\DSLink_Test\obj\Debug\netcoreapp3.1\DSLink_Test.genruntimeconfig.cache
C:\Users\l.farina\Desktop\UCRM_stage\DSLink_Test\DSLink_Test\bin\Debug\netcoreapp3.1\DSLink.dll
C:\Users\l.farina\Desktop\UCRM_stage\DSLink_Test\DSLink_Test\obj\Debug\netcoreapp3.1\DSLink_Test.csproj.CopyComplete

View file

@ -1 +0,0 @@
9951d35de2a7aa16d30daf51510165cfcd03091c

View file

@ -1,4 +0,0 @@
// <autogenerated />
using System;
using System.Reflection;
[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(".NETCoreApp,Version=v3.1", FrameworkDisplayName = "")]

View file

@ -1,23 +0,0 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Ce code a été généré par un outil.
// Version du runtime :4.0.30319.42000
//
// Les modifications apportées à ce fichier peuvent provoquer un comportement incorrect et seront perdues si
// le code est régénéré.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("DSLink_Test")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Release")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("DSLink_Test")]
[assembly: System.Reflection.AssemblyTitleAttribute("DSLink_Test")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Généré par la classe MSBuild WriteCodeFragment.

View file

@ -1 +0,0 @@
5cc398a481358a1a40cae62ae902be38a2818d55

View file

@ -1,4 +0,0 @@
// <autogenerated />
using System;
using System.Reflection;
[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(".NETCoreApp,Version=v3.1", FrameworkDisplayName = "")]

View file

@ -1,23 +0,0 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Ce code a été généré par un outil.
// Version du runtime :4.0.30319.42000
//
// Les modifications apportées à ce fichier peuvent provoquer un comportement incorrect et seront perdues si
// le code est régénéré.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("DSLink_Test")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Test")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("DSLink_Test")]
[assembly: System.Reflection.AssemblyTitleAttribute("DSLink_Test")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Généré par la classe MSBuild WriteCodeFragment.

View file

@ -1 +0,0 @@
29ce44dbba55365cfde6500e07c1af1e99992622

View file

@ -1,67 +0,0 @@
{
"version": 3,
"targets": {
".NETCoreApp,Version=v3.1": {}
},
"libraries": {},
"projectFileDependencyGroups": {
".NETCoreApp,Version=v3.1": []
},
"packageFolders": {
"C:\\Users\\l.farina\\.nuget\\packages\\": {}
},
"project": {
"version": "1.0.0",
"restore": {
"projectUniqueName": "C:\\Users\\l.farina\\Desktop\\UCRM_stage\\DSLink_Test\\DSLink_Test\\DSLink_Test.csproj",
"projectName": "DSLink_Test",
"projectPath": "C:\\Users\\l.farina\\Desktop\\UCRM_stage\\DSLink_Test\\DSLink_Test\\DSLink_Test.csproj",
"packagesPath": "C:\\Users\\l.farina\\.nuget\\packages\\",
"outputPath": "C:\\Users\\l.farina\\Desktop\\UCRM_stage\\DSLink_Test\\DSLink_Test\\obj\\",
"projectStyle": "PackageReference",
"configFilePaths": [
"C:\\Users\\l.farina\\AppData\\Roaming\\NuGet\\NuGet.Config",
"C:\\Program Files (x86)\\NuGet\\Config\\Microsoft.VisualStudio.Offline.config"
],
"originalTargetFrameworks": [
"netcoreapp3.1"
],
"sources": {
"C:\\Program Files (x86)\\Microsoft SDKs\\NuGetPackages\\": {},
"https://api.nuget.org/v3/index.json": {}
},
"frameworks": {
"netcoreapp3.1": {
"targetAlias": "netcoreapp3.1",
"projectReferences": {}
}
},
"warningProperties": {
"warnAsError": [
"NU1605"
]
}
},
"frameworks": {
"netcoreapp3.1": {
"targetAlias": "netcoreapp3.1",
"imports": [
"net461",
"net462",
"net47",
"net471",
"net472",
"net48"
],
"assetTargetFallback": true,
"warn": true,
"frameworkReferences": {
"Microsoft.NETCore.App": {
"privateAssets": "all"
}
},
"runtimeIdentifierGraphPath": "C:\\Program Files\\dotnet\\sdk\\5.0.301\\RuntimeIdentifierGraph.json"
}
}
}
}

View file

@ -1,8 +0,0 @@
{
"version": 2,
"dgSpecHash": "1CII1sNVoGsMIQceS0aY95FTrlNLrDyIPckFdr+/8fyJTQfXUpQ/mVUsQed4bcDNBOxbdzuTUwf5lQTJvNB7rA==",
"success": true,
"projectFilePath": "C:\\Users\\l.farina\\Desktop\\UCRM_stage\\DSLink_Test\\DSLink_Test\\DSLink_Test.csproj",
"expectedPackageFiles": [],
"logs": []
}

Binary file not shown.

View file

@ -3,7 +3,9 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.31424.327
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DSLink_Test", "DSLink_Test\DSLink_Test.csproj", "{21A60B53-3AD5-4DBE-8247-C6C4CAA5436B}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RSTP_DSLink", "RSTP_DSLink\RSTP_DSLink.csproj", "{2159D007-8C77-42E2-807A-CFB57271BC47}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{3A28B0FE-3B23-4A29-9D4F-D3AD9417FF14}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -11,15 +13,15 @@ Global
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{21A60B53-3AD5-4DBE-8247-C6C4CAA5436B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{21A60B53-3AD5-4DBE-8247-C6C4CAA5436B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{21A60B53-3AD5-4DBE-8247-C6C4CAA5436B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{21A60B53-3AD5-4DBE-8247-C6C4CAA5436B}.Release|Any CPU.Build.0 = Release|Any CPU
{2159D007-8C77-42E2-807A-CFB57271BC47}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2159D007-8C77-42E2-807A-CFB57271BC47}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2159D007-8C77-42E2-807A-CFB57271BC47}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2159D007-8C77-42E2-807A-CFB57271BC47}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {85B9784F-6A1C-4696-820D-E32D7F4FF0EA}
SolutionGuid = {C77C46E8-EE7F-49DF-8262-001263A7262B}
EndGlobalSection
EndGlobal

View file

@ -0,0 +1,65 @@
using CommandLine;
namespace RTSP_DSLink
{
public enum LogLevel
{
Unspecified = -1,
Info,
Debug,
Warning,
Error
}
/// <summary>
/// This class represents the complete of set of all possible command line options
/// used not only by DSLink SDK but the calling program itself
///
/// It makes use of the CommandLineParser nuget package to supply attributes to the various
/// class members. Those attributes are then used by the parser.
/// </summary>
public class CommandLineArguments
{
[Option('b', "broker",
Required = false,
HelpText = "The connection to the DSA Broker")]
public string BrokerUrl { get; set; }
[Option('n', "name",
Required = true,
HelpText = "The display name of the DSLink within the Broker")]
public string LinkName { get; set; }
[Option('l', "log",
Required = false,
Default = LogLevel.Unspecified,
HelpText = "The log level for log messages")]
public LogLevel LogLevel { get; set; }
[Option('f', "log-file",
Required = false,
HelpText =
"The folder ending with the Path.DirectorySeparatorChar specifying the location for log files to be written")]
public string LogFileFolder { get; set; }
[Option('o', "nodes",
Required = false,
HelpText = "The filename containing the DSLink nodes")]
public string NodesFileName { get; set; }
[Option('t', "token",
Required = false,
HelpText = "The security token for the connection to the Broker")]
public string Token { get; set; }
[Option('k', "key",
Required = false,
HelpText = "The path for the stored key")]
public string KeysFolder { get; set; }
[Option('d', "dslink-json",
Required = false,
HelpText = "The alternate filename containing the contents of dslink.json")]
public string DSLinkJsonFilename { get; set; }
}
}

View file

@ -0,0 +1,348 @@
using DSLink;
using DSLink.Nodes;
using DSLink.Nodes.Actions;
using DSLink.Request;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Serilog;
using CommandLine;
using System.IO;
using RTSP_DSLink;
namespace RTSP_DSLink
{
public class RSTP_DSLink : DSLinkContainer
{
private readonly Dictionary<string, Node> _rngValues;
private readonly Random _random;
private readonly Thread _randomNumberThread;
private static void Main(string[] args)
{
Parser.Default.ParseArguments<CommandLineArguments>(args)
.WithParsed(cmdLineOptions =>
{
cmdLineOptions = ProcessDSLinkJson(cmdLineOptions);
//Init the logging engine
InitializeLogging(cmdLineOptions);
//Construct a link Configuration
var config = new Configuration(cmdLineOptions.LinkName, true, true);
//Construct our custom link
var dslink = new RSTP_DSLink(config, cmdLineOptions);
InitializeLink(dslink).Wait();
})
.WithNotParsed(errors => { Environment.Exit(-1); });
while (true)
{
Thread.Sleep(1000);
}
}
public static async Task InitializeLink(RSTP_DSLink dsLink)
{
await dsLink.Connect();
await dsLink.SaveNodes();
}
public RSTP_DSLink(Configuration config, CommandLineArguments cmdLineOptions) : base(config)
{
//Perform any configuration overrides from command line options
if (cmdLineOptions.BrokerUrl != null)
{
config.BrokerUrl = cmdLineOptions.BrokerUrl;
}
if (cmdLineOptions.Token != null)
{
config.Token = cmdLineOptions.Token;
}
if (cmdLineOptions.NodesFileName != null)
{
config.NodesFilename = cmdLineOptions.NodesFileName;
}
if (cmdLineOptions.KeysFolder != null)
{
config.KeysFolder = cmdLineOptions.KeysFolder;
}
_rngValues = new Dictionary<string, Node>();
_random = new Random();
Responder.AddNodeClass("rngAdd", delegate(Node node)
{
node.Configs.Set(ConfigType.DisplayName, new Value("Create RNG"));
node.AddParameter(new Parameter
{
Name = "rngName",
ValueType = DSLink.Nodes.ValueType.String
});
node.SetAction(new ActionHandler(Permission.Config, _createRngAction));
});
Responder.AddNodeClass("rng", delegate(Node node)
{
node.Configs.Set(ConfigType.Writable, new Value(Permission.Read.Permit));
node.Configs.Set(ConfigType.ValueType, DSLink.Nodes.ValueType.Number.TypeValue);
node.Value.Set(0);
lock (_rngValues)
{
_rngValues.Add(node.Name, node);
}
});
Responder.AddNodeClass("number", delegate (Node node)
{
node.Configs.Set(ConfigType.Writable, new Value(Permission.Read.Permit));
node.Configs.Set(ConfigType.ValueType, DSLink.Nodes.ValueType.Number.TypeValue);
node.Value.Set(0);
});
_randomNumberThread = new Thread(_updateRandomNumbers);
_randomNumberThread.Start();
}
public override void InitializeDefaultNodes()
{
Responder.SuperRoot.CreateChild("createRNG", "rngAdd").BuildNode();
}
private void _updateRandomNumbers()
{
while (Thread.CurrentThread.IsAlive)
{
lock (_rngValues)
{
foreach (var n in _rngValues)
{
Node minChild, maxChild;
n.Value.Children.TryGetValue("min", out minChild);
n.Value.Children.TryGetValue("max", out maxChild);
//Si les enfants ne sont pas initialisés, on met les valeurs de min et max à 0
// Code équivalent à :
//int min, max;
//if (minChild != null) {
// min = minChild.Value.Int;
//}
//else {
// min = 0;
//}
//if (maxChild != null) {
// max = maxChild.Value.Int;
//}
//else {
// max = 0;
//}
int min = (minChild != null ? minChild.Value.Int : 0);
int max = (maxChild != null ? maxChild.Value.Int : 0);
n.Value.Value.Set(_random.Next(min, max+1));
}
}
Thread.Sleep(10000);
}
}
private async void _createRngAction(InvokeRequest request)
{
var rngName = request.Parameters["rngName"].Value<string>();
if (string.IsNullOrEmpty(rngName)) return;
if (Responder.SuperRoot.Children.ContainsKey(rngName)) return;
var newRng = Responder.SuperRoot.CreateChild(rngName, "rng").BuildNode();
newRng.CreateChild("min", "number").BuildNode();
newRng.CreateChild("max", "number").BuildNode();
await request.Close();
await SaveNodes();
}
#region Initialize Logging
/// <summary>
/// This method initializes the logging engine. In this case Serilog is used, but you
/// may use a variety of logging engines so long as they are compatible with
/// Liblog (the interface used by the DSLink SDK)
/// </summary>
/// <param name="cmdLineOptions"></param>
private static void InitializeLogging(CommandLineArguments cmdLineOptions)
{
if (cmdLineOptions.LogFileFolder != null &&
!cmdLineOptions.LogFileFolder.EndsWith(Path.DirectorySeparatorChar))
{
throw new ArgumentException($"Specified LogFileFolder must end with '{Path.DirectorySeparatorChar}'");
}
var logConfig = new LoggerConfiguration();
switch (cmdLineOptions.LogLevel)
{
case LogLevel.Debug:
logConfig.MinimumLevel.Debug();
break;
case LogLevel.Unspecified:
case LogLevel.Info:
logConfig.MinimumLevel.Information();
break;
case LogLevel.Warning:
logConfig.MinimumLevel.Warning();
break;
case LogLevel.Error:
logConfig.MinimumLevel.Error();
break;
}
logConfig.WriteTo.Console(
outputTemplate:
"{Timestamp:MM/dd/yyyy HH:mm:ss} {SourceContext} [{Level}] {Message}{NewLine}{Exception}");
logConfig.WriteTo.Logger(lc =>
{
lc.WriteTo.RollingFile(cmdLineOptions.LogFileFolder + "log-{Date}.txt", retainedFileCountLimit: 3);
});
Log.Logger = logConfig.CreateLogger();
}
#endregion
#region dslink-json file processing
/// <summary>
/// This method will return an instance of CommandLineArguments build with the following logic rules.
/// The file dslink.json can be utilized to specifiy command line arguments. These live within the config block
/// of the file. Here is an example:
/// ...
/// "configs" : {
/// "broker" : {
/// "type": "url",
/// "value": "mybroker",
/// "default": "http:localhost:8080\conn"
/// },
/// }
///
/// The code in this method considers only the attribute's name ("broker") and value ("mybroker") in this example).
/// "type" and "default" are not used.
///
/// The receives an instance of CommandLineArguments previously built from the parser. If the dslink-json paramater
/// is not null the code will use the value specified rather than the default value of "dslink.json" for the file
/// to read containing the information.
///
/// Options specified on the command line wins out over those specified in the file.
///
/// </summary>
/// <param name="cmdLineOptions"></param>
/// <returns></returns>
private static CommandLineArguments ProcessDSLinkJson(CommandLineArguments cmdLineOptions)
{
bool errorIfNotFound = false;
string fileName = "dslink.json";
//If filename is specified then error if it is not found
if (!String.IsNullOrEmpty(cmdLineOptions.DSLinkJsonFilename))
{
errorIfNotFound = true;
fileName = cmdLineOptions.DSLinkJsonFilename;
}
string fileData = "";
if (File.Exists(fileName))
{
fileData = File.ReadAllText(fileName);
Console.WriteLine(
$"Will use a combination of options specified from the command line and those specified in {fileName}");
}
else
{
if (errorIfNotFound == true)
{
throw new ArgumentException($"Specified dslink-json file <{fileName}> was not found");
}
else
{
return cmdLineOptions;
}
}
JObject dslinkJson = JObject.Parse(fileData);
var dsLinkJsonConfig = dslinkJson["configs"];
var cmdLineOptionsDslinkJson = new CommandLineArguments();
cmdLineOptionsDslinkJson.BrokerUrl =
GetDsLinkStringValueForAttributeName(dsLinkJsonConfig, "broker", cmdLineOptions.BrokerUrl);
cmdLineOptionsDslinkJson.LinkName =
GetDsLinkStringValueForAttributeName(dsLinkJsonConfig, "name", cmdLineOptions.LinkName);
cmdLineOptionsDslinkJson.LogFileFolder =
GetDsLinkStringValueForAttributeName(dsLinkJsonConfig, "log-file", cmdLineOptions.LogFileFolder);
cmdLineOptionsDslinkJson.KeysFolder =
GetDsLinkStringValueForAttributeName(dsLinkJsonConfig, "key", cmdLineOptions.KeysFolder);
cmdLineOptionsDslinkJson.NodesFileName =
GetDsLinkStringValueForAttributeName(dsLinkJsonConfig, "nodes", cmdLineOptions.NodesFileName);
cmdLineOptionsDslinkJson.Token =
GetDsLinkStringValueForAttributeName(dsLinkJsonConfig, "token", cmdLineOptions.Token);
cmdLineOptionsDslinkJson.LogLevel = GetDsLinkLogLevel(dsLinkJsonConfig, cmdLineOptions.LogLevel);
return cmdLineOptionsDslinkJson;
}
private static LogLevel GetDsLinkLogLevel(JToken configObj, LogLevel logLevel)
{
if (logLevel != LogLevel.Unspecified)
{
return logLevel;
}
string testString = "";
try
{
testString = configObj["log"]["value"].ToString();
}
catch
{
}
;
LogLevel useLogLevel = LogLevel.Info;
if (!Enum.TryParse(testString, out useLogLevel))
{
throw new ArgumentException("Invalid 'value' specified for 'log' value in dslink-json file");
}
return useLogLevel;
}
private static string GetDsLinkStringValueForAttributeName(JToken configObj, string attributeName,
string cmdLineValue)
{
//use cmdLineValue if specified else attempt to use the one from the dslink-json
if (cmdLineValue != null)
{
return cmdLineValue;
}
try
{
return configObj[attributeName]["value"].ToString();
}
catch
{
return null;
}
}
#endregion processingq
}
}

View file

@ -0,0 +1,33 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="CommandLineParser" Version="2.8.0" />
<PackageReference Include="LibLog" Version="5.0.8">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.CSharp" Version="4.7.0" />
<PackageReference Include="MsgPack.Cli" Version="1.0.1" />
<PackageReference Include="NETStandard.Library" Version="2.0.3" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="Portable.BouncyCastle" Version="1.8.10" />
<PackageReference Include="Serilog" Version="2.10.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="4.0.0" />
<PackageReference Include="Serilog.Sinks.Debug" Version="2.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
<PackageReference Include="Serilog.Sinks.RollingFile" Version="3.3.0" />
<PackageReference Include="StandardStorage" Version="0.1.1" />
</ItemGroup>
<ItemGroup>
<Reference Include="DSLink">
<HintPath>DSLink.dll</HintPath>
</Reference>
</ItemGroup>
</Project>

View file

@ -0,0 +1,578 @@
{
"runtimeTarget": {
"name": ".NETCoreApp,Version=v3.1",
"signature": ""
},
"compilationOptions": {},
"targets": {
".NETCoreApp,Version=v3.1": {
"RSTP_DSLink/1.0.0": {
"dependencies": {
"CommandLineParser": "2.8.0",
"LibLog": "5.0.8",
"Microsoft.CSharp": "4.7.0",
"MsgPack.Cli": "1.0.1",
"NETStandard.Library": "2.0.3",
"Newtonsoft.Json": "13.0.1",
"Portable.BouncyCastle": "1.8.10",
"Serilog": "2.10.0",
"Serilog.Sinks.Console": "4.0.0",
"Serilog.Sinks.Debug": "2.0.0",
"Serilog.Sinks.File": "5.0.0",
"Serilog.Sinks.RollingFile": "3.3.0",
"StandardStorage": "0.1.1",
"DSLink": "1.0.0.0"
},
"runtime": {
"RSTP_DSLink.dll": {}
}
},
"CommandLineParser/2.8.0": {
"runtime": {
"lib/netstandard2.0/CommandLine.dll": {
"assemblyVersion": "2.8.0.0",
"fileVersion": "2.8.0.0"
}
}
},
"LibLog/5.0.8": {},
"Microsoft.CSharp/4.7.0": {},
"Microsoft.NETCore.Platforms/2.0.0": {},
"Microsoft.NETCore.Targets/1.1.0": {},
"MsgPack.Cli/1.0.1": {
"dependencies": {
"System.CodeDom": "4.4.0",
"System.Numerics.Vectors": "4.3.0",
"System.Reflection.Emit": "4.3.0",
"System.Reflection.Emit.Lightweight": "4.3.0"
},
"runtime": {
"lib/netstandard2.0/MsgPack.dll": {
"assemblyVersion": "1.0.0.0",
"fileVersion": "1.0.228.0"
}
}
},
"NETStandard.Library/2.0.3": {
"dependencies": {
"Microsoft.NETCore.Platforms": "2.0.0"
}
},
"Newtonsoft.Json/13.0.1": {
"runtime": {
"lib/netstandard2.0/Newtonsoft.Json.dll": {
"assemblyVersion": "13.0.0.0",
"fileVersion": "13.0.1.25517"
}
}
},
"Portable.BouncyCastle/1.8.10": {
"runtime": {
"lib/netstandard2.0/BouncyCastle.Crypto.dll": {
"assemblyVersion": "1.8.10.0",
"fileVersion": "1.8.10.1"
}
}
},
"Serilog/2.10.0": {
"runtime": {
"lib/netstandard2.1/Serilog.dll": {
"assemblyVersion": "2.0.0.0",
"fileVersion": "2.10.0.0"
}
}
},
"Serilog.Sinks.Console/4.0.0": {
"dependencies": {
"Serilog": "2.10.0"
},
"runtime": {
"lib/netstandard2.0/Serilog.Sinks.Console.dll": {
"assemblyVersion": "4.0.0.0",
"fileVersion": "4.0.0.0"
}
}
},
"Serilog.Sinks.Debug/2.0.0": {
"dependencies": {
"Serilog": "2.10.0"
},
"runtime": {
"lib/netstandard2.1/Serilog.Sinks.Debug.dll": {
"assemblyVersion": "2.0.0.0",
"fileVersion": "2.0.0.0"
}
}
},
"Serilog.Sinks.File/5.0.0": {
"dependencies": {
"Serilog": "2.10.0"
},
"runtime": {
"lib/netstandard2.1/Serilog.Sinks.File.dll": {
"assemblyVersion": "5.0.0.0",
"fileVersion": "5.0.0.0"
}
}
},
"Serilog.Sinks.RollingFile/3.3.0": {
"dependencies": {
"Serilog.Sinks.File": "5.0.0",
"System.IO": "4.3.0",
"System.IO.FileSystem.Primitives": "4.0.1",
"System.Runtime.InteropServices": "4.1.0",
"System.Text.Encoding.Extensions": "4.0.11"
},
"runtime": {
"lib/netstandard1.3/Serilog.Sinks.RollingFile.dll": {
"assemblyVersion": "2.0.0.0",
"fileVersion": "3.3.0.0"
}
}
},
"StandardStorage/0.1.1": {
"dependencies": {
"System.Security.Permissions": "4.4.1"
},
"runtime": {
"lib/netstandard2.0/StandardStorage.dll": {
"assemblyVersion": "1.0.0.0",
"fileVersion": "1.0.0.0"
}
}
},
"System.CodeDom/4.4.0": {
"runtime": {
"lib/netstandard2.0/System.CodeDom.dll": {
"assemblyVersion": "4.0.0.0",
"fileVersion": "4.6.25519.3"
}
}
},
"System.Globalization/4.3.0": {
"dependencies": {
"Microsoft.NETCore.Platforms": "2.0.0",
"Microsoft.NETCore.Targets": "1.1.0",
"System.Runtime": "4.3.0"
}
},
"System.IO/4.3.0": {
"dependencies": {
"Microsoft.NETCore.Platforms": "2.0.0",
"Microsoft.NETCore.Targets": "1.1.0",
"System.Runtime": "4.3.0",
"System.Text.Encoding": "4.3.0",
"System.Threading.Tasks": "4.3.0"
}
},
"System.IO.FileSystem.Primitives/4.0.1": {
"dependencies": {
"System.Runtime": "4.3.0"
}
},
"System.Numerics.Vectors/4.3.0": {
"dependencies": {
"System.Globalization": "4.3.0",
"System.Resources.ResourceManager": "4.3.0",
"System.Runtime": "4.3.0",
"System.Runtime.Extensions": "4.3.0"
}
},
"System.Reflection/4.3.0": {
"dependencies": {
"Microsoft.NETCore.Platforms": "2.0.0",
"Microsoft.NETCore.Targets": "1.1.0",
"System.IO": "4.3.0",
"System.Reflection.Primitives": "4.3.0",
"System.Runtime": "4.3.0"
}
},
"System.Reflection.Emit/4.3.0": {
"dependencies": {
"System.IO": "4.3.0",
"System.Reflection": "4.3.0",
"System.Reflection.Emit.ILGeneration": "4.3.0",
"System.Reflection.Primitives": "4.3.0",
"System.Runtime": "4.3.0"
}
},
"System.Reflection.Emit.ILGeneration/4.3.0": {
"dependencies": {
"System.Reflection": "4.3.0",
"System.Reflection.Primitives": "4.3.0",
"System.Runtime": "4.3.0"
}
},
"System.Reflection.Emit.Lightweight/4.3.0": {
"dependencies": {
"System.Reflection": "4.3.0",
"System.Reflection.Emit.ILGeneration": "4.3.0",
"System.Reflection.Primitives": "4.3.0",
"System.Runtime": "4.3.0"
}
},
"System.Reflection.Primitives/4.3.0": {
"dependencies": {
"Microsoft.NETCore.Platforms": "2.0.0",
"Microsoft.NETCore.Targets": "1.1.0",
"System.Runtime": "4.3.0"
}
},
"System.Resources.ResourceManager/4.3.0": {
"dependencies": {
"Microsoft.NETCore.Platforms": "2.0.0",
"Microsoft.NETCore.Targets": "1.1.0",
"System.Globalization": "4.3.0",
"System.Reflection": "4.3.0",
"System.Runtime": "4.3.0"
}
},
"System.Runtime/4.3.0": {
"dependencies": {
"Microsoft.NETCore.Platforms": "2.0.0",
"Microsoft.NETCore.Targets": "1.1.0"
}
},
"System.Runtime.Extensions/4.3.0": {
"dependencies": {
"Microsoft.NETCore.Platforms": "2.0.0",
"Microsoft.NETCore.Targets": "1.1.0",
"System.Runtime": "4.3.0"
}
},
"System.Runtime.Handles/4.0.1": {
"dependencies": {
"Microsoft.NETCore.Platforms": "2.0.0",
"Microsoft.NETCore.Targets": "1.1.0",
"System.Runtime": "4.3.0"
}
},
"System.Runtime.InteropServices/4.1.0": {
"dependencies": {
"Microsoft.NETCore.Platforms": "2.0.0",
"Microsoft.NETCore.Targets": "1.1.0",
"System.Reflection": "4.3.0",
"System.Reflection.Primitives": "4.3.0",
"System.Runtime": "4.3.0",
"System.Runtime.Handles": "4.0.1"
}
},
"System.Security.AccessControl/4.4.0": {
"dependencies": {
"Microsoft.NETCore.Platforms": "2.0.0",
"System.Security.Principal.Windows": "4.4.0"
}
},
"System.Security.Permissions/4.4.1": {
"dependencies": {
"System.Security.AccessControl": "4.4.0"
},
"runtime": {
"lib/netstandard2.0/System.Security.Permissions.dll": {
"assemblyVersion": "4.0.0.0",
"fileVersion": "4.6.25921.2"
}
}
},
"System.Security.Principal.Windows/4.4.0": {
"dependencies": {
"Microsoft.NETCore.Platforms": "2.0.0"
}
},
"System.Text.Encoding/4.3.0": {
"dependencies": {
"Microsoft.NETCore.Platforms": "2.0.0",
"Microsoft.NETCore.Targets": "1.1.0",
"System.Runtime": "4.3.0"
}
},
"System.Text.Encoding.Extensions/4.0.11": {
"dependencies": {
"Microsoft.NETCore.Platforms": "2.0.0",
"Microsoft.NETCore.Targets": "1.1.0",
"System.Runtime": "4.3.0",
"System.Text.Encoding": "4.3.0"
}
},
"System.Threading.Tasks/4.3.0": {
"dependencies": {
"Microsoft.NETCore.Platforms": "2.0.0",
"Microsoft.NETCore.Targets": "1.1.0",
"System.Runtime": "4.3.0"
}
},
"DSLink/1.0.0.0": {
"runtime": {
"DSLink.dll": {
"assemblyVersion": "1.0.0.0",
"fileVersion": "1.0.0.0"
}
}
}
}
},
"libraries": {
"RSTP_DSLink/1.0.0": {
"type": "project",
"serviceable": false,
"sha512": ""
},
"CommandLineParser/2.8.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-eco2HlKQBY4Joz9odHigzGpVzv6pjsXnY5lziioMveQxr+i2Z7xYcIOMeZTgYiqnMtMAbXMXsVhrNfWO5vJS8Q==",
"path": "commandlineparser/2.8.0",
"hashPath": "commandlineparser.2.8.0.nupkg.sha512"
},
"LibLog/5.0.8": {
"type": "package",
"serviceable": true,
"sha512": "sha512-kRbiSI/lNkGgRr4d4iy8fmjRcolOSnPUjxfuV1QK9S4IOdEOLJf8ofc1ob6XP5+GQONJfEKMEWitL/ezxdG4GQ==",
"path": "liblog/5.0.8",
"hashPath": "liblog.5.0.8.nupkg.sha512"
},
"Microsoft.CSharp/4.7.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-pTj+D3uJWyN3My70i2Hqo+OXixq3Os2D1nJ2x92FFo6sk8fYS1m1WLNTs0Dc1uPaViH0YvEEwvzddQ7y4rhXmA==",
"path": "microsoft.csharp/4.7.0",
"hashPath": "microsoft.csharp.4.7.0.nupkg.sha512"
},
"Microsoft.NETCore.Platforms/2.0.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-VdLJOCXhZaEMY7Hm2GKiULmn7IEPFE4XC5LPSfBVCUIA8YLZVh846gtfBJalsPQF2PlzdD7ecX7DZEulJ402ZQ==",
"path": "microsoft.netcore.platforms/2.0.0",
"hashPath": "microsoft.netcore.platforms.2.0.0.nupkg.sha512"
},
"Microsoft.NETCore.Targets/1.1.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-aOZA3BWfz9RXjpzt0sRJJMjAscAUm3Hoa4UWAfceV9UTYxgwZ1lZt5nO2myFf+/jetYQo4uTP7zS8sJY67BBxg==",
"path": "microsoft.netcore.targets/1.1.0",
"hashPath": "microsoft.netcore.targets.1.1.0.nupkg.sha512"
},
"MsgPack.Cli/1.0.1": {
"type": "package",
"serviceable": true,
"sha512": "sha512-od0WujAAuPuRLoGfGNfE2iRPP7Kj+o174Oed2uirT03/Dp4rkccnEIqQl/QRHjly79sMwh6xKaIVsLqYwWtiHA==",
"path": "msgpack.cli/1.0.1",
"hashPath": "msgpack.cli.1.0.1.nupkg.sha512"
},
"NETStandard.Library/2.0.3": {
"type": "package",
"serviceable": true,
"sha512": "sha512-st47PosZSHrjECdjeIzZQbzivYBJFv6P2nv4cj2ypdI204DO+vZ7l5raGMiX4eXMJ53RfOIg+/s4DHVZ54Nu2A==",
"path": "netstandard.library/2.0.3",
"hashPath": "netstandard.library.2.0.3.nupkg.sha512"
},
"Newtonsoft.Json/13.0.1": {
"type": "package",
"serviceable": true,
"sha512": "sha512-ppPFpBcvxdsfUonNcvITKqLl3bqxWbDCZIzDWHzjpdAHRFfZe0Dw9HmA0+za13IdyrgJwpkDTDA9fHaxOrt20A==",
"path": "newtonsoft.json/13.0.1",
"hashPath": "newtonsoft.json.13.0.1.nupkg.sha512"
},
"Portable.BouncyCastle/1.8.10": {
"type": "package",
"serviceable": true,
"sha512": "sha512-XLhjNAwuVB9ynwn11l5K44eyozh8q6gFseTrlnLNttejimglX7+F9+vxh60LPjvA/DAt6fUdS43N3ah8K6eaWg==",
"path": "portable.bouncycastle/1.8.10",
"hashPath": "portable.bouncycastle.1.8.10.nupkg.sha512"
},
"Serilog/2.10.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-+QX0hmf37a0/OZLxM3wL7V6/ADvC1XihXN4Kq/p6d8lCPfgkRdiuhbWlMaFjR9Av0dy5F0+MBeDmDdRZN/YwQA==",
"path": "serilog/2.10.0",
"hashPath": "serilog.2.10.0.nupkg.sha512"
},
"Serilog.Sinks.Console/4.0.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-yJQit9sTJ4xGLKgCujqDJsaGqBNJwGB/H898z+xYlMG06twy4//6LLnSrsmpduZxcHIG4im7cv+JmXLzXz2EkQ==",
"path": "serilog.sinks.console/4.0.0",
"hashPath": "serilog.sinks.console.4.0.0.nupkg.sha512"
},
"Serilog.Sinks.Debug/2.0.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-Y6g3OBJ4JzTyyw16fDqtFcQ41qQAydnEvEqmXjhwhgjsnG/FaJ8GUqF5ldsC/bVkK8KYmqrPhDO+tm4dF6xx4A==",
"path": "serilog.sinks.debug/2.0.0",
"hashPath": "serilog.sinks.debug.2.0.0.nupkg.sha512"
},
"Serilog.Sinks.File/5.0.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-uwV5hdhWPwUH1szhO8PJpFiahqXmzPzJT/sOijH/kFgUx+cyoDTMM8MHD0adw9+Iem6itoibbUXHYslzXsLEAg==",
"path": "serilog.sinks.file/5.0.0",
"hashPath": "serilog.sinks.file.5.0.0.nupkg.sha512"
},
"Serilog.Sinks.RollingFile/3.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-2lT5X1r3GH4P0bRWJfhA7etGl8Q2Ipw9AACvtAHWRUSpYZ42NGVyHoVs2ALBZ/cAkkS+tA4jl80Zie144eLQPg==",
"path": "serilog.sinks.rollingfile/3.3.0",
"hashPath": "serilog.sinks.rollingfile.3.3.0.nupkg.sha512"
},
"StandardStorage/0.1.1": {
"type": "package",
"serviceable": true,
"sha512": "sha512-zi7/3LSxFqCu0e+x5pMGprnuWkwD5G3ZFaDaWzV/kViB12iuVQIVrW03NxjzgcBf3Q5ZAp0l1DdFHSmKR6xBpw==",
"path": "standardstorage/0.1.1",
"hashPath": "standardstorage.0.1.1.nupkg.sha512"
},
"System.CodeDom/4.4.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-2sCCb7doXEwtYAbqzbF/8UAeDRMNmPaQbU2q50Psg1J9KzumyVVCgKQY8s53WIPTufNT0DpSe9QRvVjOzfDWBA==",
"path": "system.codedom/4.4.0",
"hashPath": "system.codedom.4.4.0.nupkg.sha512"
},
"System.Globalization/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-kYdVd2f2PAdFGblzFswE4hkNANJBKRmsfa2X5LG2AcWE1c7/4t0pYae1L8vfZ5xvE2nK/R9JprtToA61OSHWIg==",
"path": "system.globalization/4.3.0",
"hashPath": "system.globalization.4.3.0.nupkg.sha512"
},
"System.IO/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-3qjaHvxQPDpSOYICjUoTsmoq5u6QJAFRUITgeT/4gqkF1bajbSmb1kwSxEA8AHlofqgcKJcM8udgieRNhaJ5Cg==",
"path": "system.io/4.3.0",
"hashPath": "system.io.4.3.0.nupkg.sha512"
},
"System.IO.FileSystem.Primitives/4.0.1": {
"type": "package",
"serviceable": true,
"sha512": "sha512-kWkKD203JJKxJeE74p8aF8y4Qc9r9WQx4C0cHzHPrY3fv/L/IhWnyCHaFJ3H1QPOH6A93whlQ2vG5nHlBDvzWQ==",
"path": "system.io.filesystem.primitives/4.0.1",
"hashPath": "system.io.filesystem.primitives.4.0.1.nupkg.sha512"
},
"System.Numerics.Vectors/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-uAIqmwiQPPXdCz59MQcyHwsH2MzIv24VGCS54kP/1GzTRTuU3hazmiPnGUTlKFia4B1DnbLWjTHoGyTI5BMCTQ==",
"path": "system.numerics.vectors/4.3.0",
"hashPath": "system.numerics.vectors.4.3.0.nupkg.sha512"
},
"System.Reflection/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-KMiAFoW7MfJGa9nDFNcfu+FpEdiHpWgTcS2HdMpDvt9saK3y/G4GwprPyzqjFH9NTaGPQeWNHU+iDlDILj96aQ==",
"path": "system.reflection/4.3.0",
"hashPath": "system.reflection.4.3.0.nupkg.sha512"
},
"System.Reflection.Emit/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-228FG0jLcIwTVJyz8CLFKueVqQK36ANazUManGaJHkO0icjiIypKW7YLWLIWahyIkdh5M7mV2dJepllLyA1SKg==",
"path": "system.reflection.emit/4.3.0",
"hashPath": "system.reflection.emit.4.3.0.nupkg.sha512"
},
"System.Reflection.Emit.ILGeneration/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-59tBslAk9733NXLrUJrwNZEzbMAcu8k344OYo+wfSVygcgZ9lgBdGIzH/nrg3LYhXceynyvTc8t5/GD4Ri0/ng==",
"path": "system.reflection.emit.ilgeneration/4.3.0",
"hashPath": "system.reflection.emit.ilgeneration.4.3.0.nupkg.sha512"
},
"System.Reflection.Emit.Lightweight/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-oadVHGSMsTmZsAF864QYN1t1QzZjIcuKU3l2S9cZOwDdDueNTrqq1yRj7koFfIGEnKpt6NjpL3rOzRhs4ryOgA==",
"path": "system.reflection.emit.lightweight/4.3.0",
"hashPath": "system.reflection.emit.lightweight.4.3.0.nupkg.sha512"
},
"System.Reflection.Primitives/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-5RXItQz5As4xN2/YUDxdpsEkMhvw3e6aNveFXUn4Hl/udNTCNhnKp8lT9fnc3MhvGKh1baak5CovpuQUXHAlIA==",
"path": "system.reflection.primitives/4.3.0",
"hashPath": "system.reflection.primitives.4.3.0.nupkg.sha512"
},
"System.Resources.ResourceManager/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-/zrcPkkWdZmI4F92gL/TPumP98AVDu/Wxr3CSJGQQ+XN6wbRZcyfSKVoPo17ilb3iOr0cCRqJInGwNMolqhS8A==",
"path": "system.resources.resourcemanager/4.3.0",
"hashPath": "system.resources.resourcemanager.4.3.0.nupkg.sha512"
},
"System.Runtime/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-JufQi0vPQ0xGnAczR13AUFglDyVYt4Kqnz1AZaiKZ5+GICq0/1MH/mO/eAJHt/mHW1zjKBJd7kV26SrxddAhiw==",
"path": "system.runtime/4.3.0",
"hashPath": "system.runtime.4.3.0.nupkg.sha512"
},
"System.Runtime.Extensions/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-guW0uK0fn5fcJJ1tJVXYd7/1h5F+pea1r7FLSOz/f8vPEqbR2ZAknuRDvTQ8PzAilDveOxNjSfr0CHfIQfFk8g==",
"path": "system.runtime.extensions/4.3.0",
"hashPath": "system.runtime.extensions.4.3.0.nupkg.sha512"
},
"System.Runtime.Handles/4.0.1": {
"type": "package",
"serviceable": true,
"sha512": "sha512-nCJvEKguXEvk2ymk1gqj625vVnlK3/xdGzx0vOKicQkoquaTBJTP13AIYkocSUwHCLNBwUbXTqTWGDxBTWpt7g==",
"path": "system.runtime.handles/4.0.1",
"hashPath": "system.runtime.handles.4.0.1.nupkg.sha512"
},
"System.Runtime.InteropServices/4.1.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-16eu3kjHS633yYdkjwShDHZLRNMKVi/s0bY8ODiqJ2RfMhDMAwxZaUaWVnZ2P71kr/or+X9o/xFWtNqz8ivieQ==",
"path": "system.runtime.interopservices/4.1.0",
"hashPath": "system.runtime.interopservices.4.1.0.nupkg.sha512"
},
"System.Security.AccessControl/4.4.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-2NRFPX/V81ucKQmqNgGBZrKGH/5ejsvivSGMRum0SMgPnJxwhuNkzVS1+7gC3R2X0f57CtwrPrXPPSe6nOp82g==",
"path": "system.security.accesscontrol/4.4.0",
"hashPath": "system.security.accesscontrol.4.4.0.nupkg.sha512"
},
"System.Security.Permissions/4.4.1": {
"type": "package",
"serviceable": true,
"sha512": "sha512-l8IxQ9mEAkKv85uoEcjcYhrh+yTLZtLgNqb2T7QChTdKXh45EUnmKd+Ckdt1D+VYW2dk2Pb5MT+0zwQ74Jd2Xg==",
"path": "system.security.permissions/4.4.1",
"hashPath": "system.security.permissions.4.4.1.nupkg.sha512"
},
"System.Security.Principal.Windows/4.4.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-pP+AOzt1o3jESOuLmf52YQTF7H3Ng9hTnrOESQiqsnl2IbBh1HInsAMHYtoh75iUYV0OIkHmjvveraYB6zM97w==",
"path": "system.security.principal.windows/4.4.0",
"hashPath": "system.security.principal.windows.4.4.0.nupkg.sha512"
},
"System.Text.Encoding/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-BiIg+KWaSDOITze6jGQynxg64naAPtqGHBwDrLaCtixsa5bKiR8dpPOHA7ge3C0JJQizJE+sfkz1wV+BAKAYZw==",
"path": "system.text.encoding/4.3.0",
"hashPath": "system.text.encoding.4.3.0.nupkg.sha512"
},
"System.Text.Encoding.Extensions/4.0.11": {
"type": "package",
"serviceable": true,
"sha512": "sha512-jtbiTDtvfLYgXn8PTfWI+SiBs51rrmO4AAckx4KR6vFK9Wzf6tI8kcRdsYQNwriUeQ1+CtQbM1W4cMbLXnj/OQ==",
"path": "system.text.encoding.extensions/4.0.11",
"hashPath": "system.text.encoding.extensions.4.0.11.nupkg.sha512"
},
"System.Threading.Tasks/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-LbSxKEdOUhVe8BezB/9uOGGppt+nZf6e1VFyw6v3DN6lqitm0OSn2uXMOdtP0M3W4iMcqcivm2J6UgqiwwnXiA==",
"path": "system.threading.tasks/4.3.0",
"hashPath": "system.threading.tasks.4.3.0.nupkg.sha512"
},
"DSLink/1.0.0.0": {
"type": "reference",
"serviceable": false,
"sha512": ""
}
}
}

View file

@ -0,0 +1,33 @@
// <auto-generated/>
// ReSharper disable CheckNamespace
namespace RSTP_DSLink.Logging
{
using System;
/// <summary>
/// Simple interface that represent a logger.
/// </summary>
#if LIBLOG_PUBLIC
public
#else
internal
#endif
interface ILog
{
/// <summary>
/// Log a message the specified log level.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <param name="messageFunc">The message function.</param>
/// <param name="exception">An optional exception.</param>
/// <param name="formatParameters">Optional format parameters for the message generated by the messagefunc. </param>
/// <returns>true if the message was logged. Otherwise false.</returns>
/// <remarks>
/// Note to implementers: the message func should not be called if the loglevel is not enabled
/// so as not to incur performance penalties.
/// To check IsEnabled call Log with only LogLevel and check the return value, no event will be written.
/// </remarks>
bool Log(LogLevel logLevel, Func<string> messageFunc, Exception exception = null,
params object[] formatParameters);
}
}

View file

@ -0,0 +1,40 @@
// <auto-generated/>
// ReSharper disable CheckNamespace
using System;
namespace RSTP_DSLink.Logging
{
/// <summary>
/// Represents a way to get a <see cref="Logger"/>
/// </summary>
#if LIBLOG_PROVIDERS_ONLY
internal
#else
public
#endif
interface ILogProvider
{
/// <summary>
/// Gets the specified named logger.
/// </summary>
/// <param name="name">Name of the logger.</param>
/// <returns>The logger reference.</returns>
Logger GetLogger(string name);
/// <summary>
/// Opens a nested diagnostics context. Not supported in EntLib logging.
/// </summary>
/// <param name="message">The message to add to the diagnostics context.</param>
/// <returns>A disposable that when disposed removes the message from the context.</returns>
IDisposable OpenNestedContext(string message);
/// <summary>
/// Opens a mapped diagnostics context. Not supported in EntLib logging.
/// </summary>
/// <param name="key">A key.</param>
/// <param name="value">A value.</param>
/// <param name="destructure">Determines whether to call the destructor or not.</param>
/// <returns>A disposable that when disposed removes the map from the context.</returns>
IDisposable OpenMappedContext(string key, object value, bool destructure = false);
}
}

View file

@ -0,0 +1,562 @@
// <auto-generated/>
// ReSharper disable CheckNamespace
namespace RSTP_DSLink.Logging
{
using System;
#if LIBLOG_EXCLUDE_CODE_COVERAGE
using System.Diagnostics.CodeAnalysis;
#endif
/// <summary>
/// Extension methods for the <see cref="ILog"/> interface.
/// </summary>
#if LIBLOG_EXCLUDE_CODE_COVERAGE
[ExcludeFromCodeCoverage]
#endif
#if LIBLOG_PUBLIC
public
#else
internal
#endif
static class LogExtensions
{
internal static readonly object[] EmptyParams = new object[0];
/// <summary>
/// Check if the <see cref="LogLevel.Debug"/> log level is enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to check with.</param>
/// <returns>True if the log level is enabled; false otherwise.</returns>
public static bool IsDebugEnabled(this ILog logger)
{
GuardAgainstNullLogger(logger);
return logger.Log(LogLevel.Debug, null, null, EmptyParams);
}
/// <summary>
/// Check if the <see cref="LogLevel.Error"/> log level is enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to check with.</param>
/// <returns>True if the log level is enabled; false otherwise.</returns>
public static bool IsErrorEnabled(this ILog logger)
{
GuardAgainstNullLogger(logger);
return logger.Log(LogLevel.Error, null, null, EmptyParams);
}
/// <summary>
/// Check if the <see cref="LogLevel.Fatal"/> log level is enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to check with.</param>
/// <returns>True if the log level is enabled; false otherwise.</returns>
public static bool IsFatalEnabled(this ILog logger)
{
GuardAgainstNullLogger(logger);
return logger.Log(LogLevel.Fatal, null, null, EmptyParams);
}
/// <summary>
/// Check if the <see cref="LogLevel.Info"/> log level is enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to check with.</param>
/// <returns>True if the log level is enabled; false otherwise.</returns>
public static bool IsInfoEnabled(this ILog logger)
{
GuardAgainstNullLogger(logger);
return logger.Log(LogLevel.Info, null, null, EmptyParams);
}
/// <summary>
/// Check if the <see cref="LogLevel.Trace"/> log level is enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to check with.</param>
/// <returns>True if the log level is enabled; false otherwise.</returns>
public static bool IsTraceEnabled(this ILog logger)
{
GuardAgainstNullLogger(logger);
return logger.Log(LogLevel.Trace, null, null, EmptyParams);
}
/// <summary>
/// Check if the <see cref="LogLevel.Warn"/> log level is enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to check with.</param>
/// <returns>True if the log level is enabled; false otherwise.</returns>
public static bool IsWarnEnabled(this ILog logger)
{
GuardAgainstNullLogger(logger);
return logger.Log(LogLevel.Warn, null, null, EmptyParams);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Debug"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to use.</param>
/// <param name="messageFunc">The message function.</param>
public static void Debug(this ILog logger, Func<string> messageFunc)
{
GuardAgainstNullLogger(logger);
logger.Log(LogLevel.Debug, WrapLogInternal(messageFunc), null, EmptyParams);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Debug"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to use.</param>
/// <param name="message">The message.</param>
public static void Debug(this ILog logger, string message)
{
if (logger.IsDebugEnabled()) logger.Log(LogLevel.Debug, message.AsFunc(), null, EmptyParams);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Debug"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to use.</param>
/// <param name="message">The message.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void Debug(this ILog logger, string message, params object[] args)
{
logger.DebugFormat(message, args);
}
/// <summary>
/// Logs an exception at the <see cref="LogLevel.Debug"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to use.</param>
/// <param name="exception">The exception.</param>
/// <param name="message">The message.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void Debug(this ILog logger, Exception exception, string message, params object[] args)
{
logger.DebugException(message, exception, args);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Debug"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to use.</param>
/// <param name="message">The message.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void DebugFormat(this ILog logger, string message, params object[] args)
{
if (logger.IsDebugEnabled()) logger.LogFormat(LogLevel.Debug, message, args);
}
/// <summary>
/// Logs an exception at the <see cref="LogLevel.Debug"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to use.</param>
/// <param name="message">The message.</param>
/// <param name="exception">The exception.</param>
public static void DebugException(this ILog logger, string message, Exception exception)
{
if (logger.IsDebugEnabled()) logger.Log(LogLevel.Debug, message.AsFunc(), exception, EmptyParams);
}
/// <summary>
/// Logs an exception at the <see cref="LogLevel.Debug"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to use.</param>
/// <param name="message">The message.</param>
/// <param name="exception">The exception.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void DebugException(this ILog logger, string message, Exception exception,
params object[] args)
{
if (logger.IsDebugEnabled()) logger.Log(LogLevel.Debug, message.AsFunc(), exception, args);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Error"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to use.</param>
/// <param name="messageFunc">The message function.</param>
public static void Error(this ILog logger, Func<string> messageFunc)
{
GuardAgainstNullLogger(logger);
logger.Log(LogLevel.Error, WrapLogInternal(messageFunc), null, EmptyParams);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Error"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to use.</param>
/// <param name="message">The message.</param>
public static void Error(this ILog logger, string message)
{
if (logger.IsErrorEnabled()) logger.Log(LogLevel.Error, message.AsFunc(), null, EmptyParams);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Error"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to use.</param>
/// <param name="message">The message.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void Error(this ILog logger, string message, params object[] args)
{
logger.ErrorFormat(message, args);
}
/// <summary>
/// Logs an exception at the <see cref="LogLevel.Error"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to use.</param>
/// <param name="exception">The exception.</param>
/// <param name="message">The message.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void Error(this ILog logger, Exception exception, string message, params object[] args)
{
logger.ErrorException(message, exception, args);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Error"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to use.</param>
/// <param name="message">The message.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void ErrorFormat(this ILog logger, string message, params object[] args)
{
if (logger.IsErrorEnabled()) logger.LogFormat(LogLevel.Error, message, args);
}
/// <summary>
/// Logs an exception at the <see cref="LogLevel.Error"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to use.</param>
/// <param name="message">The message.</param>
/// <param name="exception">The exception.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void ErrorException(this ILog logger, string message, Exception exception,
params object[] args)
{
if (logger.IsErrorEnabled()) logger.Log(LogLevel.Error, message.AsFunc(), exception, args);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Fatal"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to use.</param>
/// <param name="messageFunc">The message function.</param>
public static void Fatal(this ILog logger, Func<string> messageFunc)
{
logger.Log(LogLevel.Fatal, WrapLogInternal(messageFunc), null, EmptyParams);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Fatal"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to use.</param>
/// <param name="message">The message.</param>
public static void Fatal(this ILog logger, string message)
{
if (logger.IsFatalEnabled()) logger.Log(LogLevel.Fatal, message.AsFunc(), null, EmptyParams);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Fatal"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to use.</param>
/// <param name="message">The message.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void Fatal(this ILog logger, string message, params object[] args)
{
logger.FatalFormat(message, args);
}
/// <summary>
/// Logs an exception at the <see cref="LogLevel.Fatal"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to use.</param>
/// <param name="exception">The exception.</param>
/// <param name="message">The message.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void Fatal(this ILog logger, Exception exception, string message, params object[] args)
{
logger.FatalException(message, exception, args);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Fatal"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to use.</param>
/// <param name="message">The message.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void FatalFormat(this ILog logger, string message, params object[] args)
{
if (logger.IsFatalEnabled()) logger.LogFormat(LogLevel.Fatal, message, args);
}
/// <summary>
/// Logs an exception at the <see cref="LogLevel.Fatal"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to use.</param>
/// <param name="message">The message.</param>
/// <param name="exception">The exception.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void FatalException(this ILog logger, string message, Exception exception,
params object[] args)
{
if (logger.IsFatalEnabled()) logger.Log(LogLevel.Fatal, message.AsFunc(), exception, args);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Info"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to use.</param>
/// <param name="messageFunc">The message function.</param>
public static void Info(this ILog logger, Func<string> messageFunc)
{
GuardAgainstNullLogger(logger);
logger.Log(LogLevel.Info, WrapLogInternal(messageFunc), null, EmptyParams);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Info"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to use.</param>
/// <param name="message">The message.</param>
public static void Info(this ILog logger, string message)
{
if (logger.IsInfoEnabled()) logger.Log(LogLevel.Info, message.AsFunc(), null, EmptyParams);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Info"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to use.</param>
/// <param name="message">The message.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void Info(this ILog logger, string message, params object[] args)
{
logger.InfoFormat(message, args);
}
/// <summary>
/// Logs an exception at the <see cref="LogLevel.Info"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to use.</param>
/// <param name="exception">The exception.</param>
/// <param name="message">The message.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void Info(this ILog logger, Exception exception, string message, params object[] args)
{
logger.InfoException(message, exception, args);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Info"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to use.</param>
/// <param name="message">The message.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void InfoFormat(this ILog logger, string message, params object[] args)
{
if (logger.IsInfoEnabled()) logger.LogFormat(LogLevel.Info, message, args);
}
/// <summary>
/// Logs an exception at the <see cref="LogLevel.Info"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to use.</param>
/// <param name="message">The message.</param>
/// <param name="exception">The exception.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void InfoException(this ILog logger, string message, Exception exception,
params object[] args)
{
if (logger.IsInfoEnabled()) logger.Log(LogLevel.Info, message.AsFunc(), exception, args);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Trace"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to use.</param>
/// <param name="messageFunc">The message function.</param>
public static void Trace(this ILog logger, Func<string> messageFunc)
{
GuardAgainstNullLogger(logger);
logger.Log(LogLevel.Trace, WrapLogInternal(messageFunc), null, EmptyParams);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Trace"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to use.</param>
/// <param name="message">The message.</param>
public static void Trace(this ILog logger, string message)
{
if (logger.IsTraceEnabled()) logger.Log(LogLevel.Trace, message.AsFunc(), null, EmptyParams);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Trace"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to use.</param>
/// <param name="message">The message.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void Trace(this ILog logger, string message, params object[] args)
{
logger.TraceFormat(message, args);
}
/// <summary>
/// Logs an exception at the <see cref="LogLevel.Trace"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to use.</param>
/// <param name="exception">The exception.</param>
/// <param name="message">The message.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void Trace(this ILog logger, Exception exception, string message, params object[] args)
{
logger.TraceException(message, exception, args);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Trace"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to use.</param>
/// <param name="message">The message.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void TraceFormat(this ILog logger, string message, params object[] args)
{
if (logger.IsTraceEnabled()) logger.LogFormat(LogLevel.Trace, message, args);
}
/// <summary>
/// Logs an exception at the <see cref="LogLevel.Trace"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to use.</param>
/// <param name="message">The message.</param>
/// <param name="exception">The exception.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void TraceException(this ILog logger, string message, Exception exception,
params object[] args)
{
if (logger.IsTraceEnabled()) logger.Log(LogLevel.Trace, message.AsFunc(), exception, args);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Warn"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to use.</param>
/// <param name="messageFunc">The message function.</param>
public static void Warn(this ILog logger, Func<string> messageFunc)
{
GuardAgainstNullLogger(logger);
logger.Log(LogLevel.Warn, WrapLogInternal(messageFunc), null, EmptyParams);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Warn"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to use.</param>
/// <param name="message">The message.</param>
public static void Warn(this ILog logger, string message)
{
if (logger.IsWarnEnabled()) logger.Log(LogLevel.Warn, message.AsFunc(), null, EmptyParams);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Warn"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to use.</param>
/// <param name="message">The message.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void Warn(this ILog logger, string message, params object[] args)
{
logger.WarnFormat(message, args);
}
/// <summary>
/// Logs an exception at the <see cref="LogLevel.Warn"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to use.</param>
/// <param name="exception">The exception.</param>
/// <param name="message">The message.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void Warn(this ILog logger, Exception exception, string message, params object[] args)
{
logger.WarnException(message, exception, args);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Warn"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to use.</param>
/// <param name="message">The message.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void WarnFormat(this ILog logger, string message, params object[] args)
{
if (logger.IsWarnEnabled()) logger.LogFormat(LogLevel.Warn, message, args);
}
/// <summary>
/// Logs an exception at the <see cref="LogLevel.Warn"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILog"/> to use.</param>
/// <param name="message">The message.</param>
/// <param name="exception">The exception.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void WarnException(this ILog logger, string message, Exception exception,
params object[] args)
{
if (logger.IsWarnEnabled()) logger.Log(LogLevel.Warn, message.AsFunc(), exception, args);
}
// ReSharper disable once UnusedParameter.Local
private static void GuardAgainstNullLogger(ILog logger)
{
if (logger == null) throw new ArgumentNullException("logger");
}
private static void LogFormat(this ILog logger, LogLevel logLevel, string message, params object[] args)
{
logger.Log(logLevel, message.AsFunc(), null, args);
}
// Avoid the closure allocation, see https://gist.github.com/AArnott/d285feef75c18f6ecd2b
private static Func<T> AsFunc<T>(this T value) where T : class
{
return value.Return;
}
private static T Return<T>(this T value)
{
return value;
}
// Allow passing callsite-logger-type to LogProviderBase using messageFunc
internal static Func<string> WrapLogSafeInternal(LoggerExecutionWrapper logger, Func<string> messageFunc)
{
var WrappedMessageFunc = new Func<string>(() => {
try
{
return messageFunc();
}
catch (Exception ex)
{
logger.WrappedLogger(LogLevel.Error, () => LoggerExecutionWrapper.FailedToGenerateLogMessage, ex,
EmptyParams);
}
return null;
});
return WrappedMessageFunc;
}
// Allow passing callsite-logger-type to LogProviderBase using messageFunc
private static Func<string> WrapLogInternal(Func<string> messageFunc)
{
var WrappedMessageFunc = new Func<string>(() =>
{
return messageFunc();
});
return WrappedMessageFunc;
}
}
}

View file

@ -0,0 +1,45 @@
// <auto-generated/>
// ReSharper disable CheckNamespace
namespace RSTP_DSLink.Logging
{
/// <summary>
/// The log level.
/// </summary>
#if LIBLOG_PROVIDERS_ONLY
internal
#else
public
#endif
enum LogLevel
{
/// <summary>
/// Trace
/// </summary>
Trace,
/// <summary>
/// Debug
/// </summary>
Debug,
/// <summary>
/// Info
/// </summary>
Info,
/// <summary>
/// Warn
/// </summary>
Warn,
/// <summary>
/// Error
/// </summary>
Error,
/// <summary>
/// Fatal
/// </summary>
Fatal
}
}

View file

@ -0,0 +1,318 @@
// <auto-generated/>
// ReSharper disable CheckNamespace
//===============================================================================
// LibLog
//
// https://github.com/damianh/LibLog
//===============================================================================
// Copyright © 2011-2017 Damian Hickey. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//===============================================================================
// @formatter:off — disable resharper formatter after this line
// ReSharper disable PossibleNullReferenceException
// Define LIBLOG_PUBLIC to enable ability to GET a logger (LogProvider.For<>() etc) from outside this library. NOTE:
// this can have unintended consequences of consumers of your library using your library to resolve a logger. If the
// reason is because you want to open this functionality to other projects within your solution,
// consider [InternalsVisibleTo] instead.
//
// Define LIBLOG_PROVIDERS_ONLY if your library provides its own logging API and you just want to use the
// LibLog providers internally to provide built in support for popular logging frameworks.
#pragma warning disable 1591
using global::System.Diagnostics.CodeAnalysis;
[assembly: SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "RSTP_DSLink.Logging")]
[assembly: SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Scope = "member", Target = "RSTP_DSLink.Logging.Logger.#Invoke(RSTP_DSLink.Logging.LogLevel,System.Func`1<System.String>,System.Exception,System.Object[])")]
// If you copied this file manually, you need to change all "YourRootNameSpace" so not to clash with other libraries
// that use LibLog
namespace RSTP_DSLink.Logging
{
using global::System.Collections.Generic;
using global::System.Diagnostics.CodeAnalysis;
using global::RSTP_DSLink.Logging.LogProviders;
using global::System;
#if !LIBLOG_PROVIDERS_ONLY
using global::System.Diagnostics;
using global::System.Runtime.CompilerServices;
#endif
#if LIBLOG_EXCLUDE_CODE_COVERAGE
[ExcludeFromCodeCoverage]
#endif
#if LIBLOG_PROVIDERS_ONLY
/// <summary>
/// Provides a mechanism to set the <see cref="ILogProvider" />
/// and create instances of <see cref="ILog" /> objects.
/// </summary>
internal
#else
/// <summary>
/// Provides a mechanism to set the <see cref="ILogProvider" />.
/// </summary>
public
#endif
static class LogProvider
{
private static readonly Lazy<ILogProvider> ResolvedLogProvider = new Lazy<ILogProvider>(ForceResolveLogProvider);
#if !LIBLOG_PROVIDERS_ONLY
private static ILogProvider s_currentLogProvider;
private static Action<ILogProvider> s_onCurrentLogProviderSet;
[SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")]
static LogProvider()
{
IsDisabled = false;
}
/// <summary>
/// Sets the current log provider.
/// </summary>
/// <param name="logProvider">The log provider.</param>
public static void SetCurrentLogProvider(ILogProvider logProvider)
{
s_currentLogProvider = logProvider;
RaiseOnCurrentLogProviderSet();
}
/// <summary>
/// Gets or sets a value indicating whether this is logging is disabled.
/// </summary>
/// <value>
/// <c>true</c> if logging is disabled; otherwise, <c>false</c>.
/// </value>
public static bool IsDisabled { get; set; }
/// <summary>
/// Sets an action that is invoked when a consumer of your library has called SetCurrentLogProvider. It is
/// important that hook into this if you are using child libraries (especially ilmerged ones) that are using
/// LibLog (or other logging abstraction) so you adapt and delegate to them.
/// <see cref="SetCurrentLogProvider"/>
/// </summary>
internal static Action<ILogProvider> OnCurrentLogProviderSet
{
set
{
s_onCurrentLogProviderSet = value;
RaiseOnCurrentLogProviderSet();
}
}
internal static ILogProvider CurrentLogProvider
{
get { return s_currentLogProvider; }
}
/// <summary>
/// Gets a logger for the specified type.
/// </summary>
/// <typeparam name="T">The type whose name will be used for the logger.</typeparam>
/// <returns>An instance of <see cref="ILog"/></returns>
#if LIBLOG_PUBLIC
public
#else
internal
#endif
static ILog For<T>()
{
return GetLogger(typeof(T));
}
/// <summary>
/// Gets a logger for the current class.
/// </summary>
/// <returns>An instance of <see cref="ILog"/></returns>
[MethodImpl(MethodImplOptions.NoInlining)]
#if LIBLOG_PUBLIC
public
#else
internal
#endif
static ILog GetCurrentClassLogger()
{
var stackFrame = new StackFrame(1, false);
return GetLogger(stackFrame.GetMethod().DeclaringType);
}
/// <summary>
/// Gets a logger for the specified type.
/// </summary>
/// <param name="type">The type whose name will be used for the logger.</param>
/// <param name="fallbackTypeName">If the type is null then this name will be used as the log name instead</param>
/// <returns>An instance of <see cref="ILog"/></returns>
#if LIBLOG_PUBLIC
public
#else
internal
#endif
static ILog GetLogger(Type type, string fallbackTypeName = "System.Object")
{
// If the type passed in is null then fallback to the type name specified
return GetLogger(type != null ? type.ToString() : fallbackTypeName);
}
/// <summary>
/// Gets a logger with the specified name.
/// </summary>
/// <param name="name">The name.</param>
/// <returns>An instance of <see cref="ILog"/></returns>
#if LIBLOG_PUBLIC
public
#else
internal
#endif
static ILog GetLogger(string name)
{
var logProvider = CurrentLogProvider ?? ResolveLogProvider();
return logProvider == null
? NoOpLogger.Instance
: (ILog)new LoggerExecutionWrapper(logProvider.GetLogger(name), () => IsDisabled);
}
/// <summary>
/// Opens a nested diagnostics context.
/// </summary>
/// <param name="message">A message.</param>
/// <returns>An <see cref="IDisposable"/> that closes context when disposed.</returns>
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "SetCurrentLogProvider")]
#if LIBLOG_PUBLIC
public
#else
internal
#endif
static IDisposable OpenNestedContext(string message)
{
var logProvider = CurrentLogProvider ?? ResolveLogProvider();
return logProvider == null
? new DisposableAction(() => { })
: logProvider.OpenNestedContext(message);
}
/// <summary>
/// Opens a mapped diagnostics context.
/// </summary>
/// <param name="key">A key.</param>
/// <param name="value">A value.</param>
/// <param name="destructure">A optional paramater to indicate message should be destructured.</param>
/// <returns>An <see cref="IDisposable"/> that closes context when disposed.</returns>
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "SetCurrentLogProvider")]
#if LIBLOG_PUBLIC
public
#else
internal
#endif
static IDisposable OpenMappedContext(string key, object value, bool destructure = false)
{
var logProvider = CurrentLogProvider ?? ResolveLogProvider();
return logProvider == null
? new DisposableAction(() => { })
: logProvider.OpenMappedContext(key, value, destructure);
}
#endif
#if LIBLOG_PROVIDERS_ONLY
private
#else
internal
#endif
delegate bool IsLoggerAvailable();
#if LIBLOG_PROVIDERS_ONLY
private
#else
internal
#endif
delegate ILogProvider CreateLogProvider();
#if LIBLOG_PROVIDERS_ONLY
private
#else
internal
#endif
static readonly List<Tuple<IsLoggerAvailable, CreateLogProvider>> LogProviderResolvers =
new List<Tuple<IsLoggerAvailable, CreateLogProvider>>
{
new Tuple<IsLoggerAvailable, CreateLogProvider>(SerilogLogProvider.IsLoggerAvailable, () => new SerilogLogProvider()),
new Tuple<IsLoggerAvailable, CreateLogProvider>(NLogLogProvider.IsLoggerAvailable, () => new NLogLogProvider()),
new Tuple<IsLoggerAvailable, CreateLogProvider>(Log4NetLogProvider.IsLoggerAvailable, () => new Log4NetLogProvider()),
new Tuple<IsLoggerAvailable, CreateLogProvider>(LoupeLogProvider.IsLoggerAvailable, () => new LoupeLogProvider()),
};
#if !LIBLOG_PROVIDERS_ONLY
private static void RaiseOnCurrentLogProviderSet()
{
if (s_onCurrentLogProviderSet != null)
{
s_onCurrentLogProviderSet(s_currentLogProvider);
}
}
#endif
internal static ILogProvider ResolveLogProvider()
{
return ResolvedLogProvider.Value;
}
[SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "System.Console.WriteLine(System.String,System.Object,System.Object)")]
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
internal static ILogProvider ForceResolveLogProvider()
{
try
{
foreach (var providerResolver in LogProviderResolvers)
{
if (providerResolver.Item1())
{
return providerResolver.Item2();
}
}
}
catch (Exception ex)
{
Console.WriteLine(
"Exception occurred resolving a log provider. Logging for this assembly {0} is disabled. {1}",
typeof(LogProvider).Assembly.FullName,
ex);
}
return null;
}
#if !LIBLOG_PROVIDERS_ONLY
#if LIBLOG_EXCLUDE_CODE_COVERAGE
[ExcludeFromCodeCoverage]
#endif
internal class NoOpLogger : ILog
{
internal static readonly NoOpLogger Instance = new NoOpLogger();
public bool Log(LogLevel logLevel, Func<string> messageFunc, Exception exception, params object[] formatParameters)
{
return false;
}
}
#endif
}
}

View file

@ -0,0 +1,26 @@
// <auto-generated/>
// ReSharper disable CheckNamespace
namespace RSTP_DSLink.Logging.LogProviders
{
using System;
#if LIBLOG_EXCLUDE_CODE_COVERAGE
using System.Diagnostics.CodeAnalysis;
[ExcludeFromCodeCoverage]
#endif
internal class DisposableAction : IDisposable
{
private readonly Action _onDispose;
public DisposableAction(Action onDispose = null)
{
_onDispose = onDispose;
}
public void Dispose()
{
if(_onDispose != null) _onDispose.Invoke();
}
}
}

View file

@ -0,0 +1,42 @@
// <auto-generated/>
// ReSharper disable CheckNamespace
namespace RSTP_DSLink.Logging.LogProviders
{
using System;
#if LIBLOG_EXCLUDE_CODE_COVERAGE
using System.Diagnostics.CodeAnalysis;
#endif
#if LIBLOG_EXCLUDE_CODE_COVERAGE
[ExcludeFromCodeCoverage]
#endif
#if !LIBLOG_PROVIDERS_ONLY || LIBLOG_PUBLIC
/// <summary>
/// Exception thrown by LibLog.
/// </summary>
public
#else
internal
#endif
class LibLogException : Exception
{
/// <summary>
/// Initializes a new LibLogException with the specified message.
/// </summary>
/// <param name="message">The message</param>
public LibLogException(string message)
: base(message)
{
}
/// <summary>
/// Initializes a new LibLogException with the specified message and inner exception.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="inner">The inner exception.</param>
public LibLogException(string message, Exception inner)
: base(message, inner)
{
}
}
}

View file

@ -0,0 +1,381 @@
// <auto-generated/>
// ReSharper disable CheckNamespace
namespace RSTP_DSLink.Logging.LogProviders
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading;
#if LIBLOG_EXCLUDE_CODE_COVERAGE
[ExcludeFromCodeCoverage]
#endif
internal class Log4NetLogProvider : LogProviderBase
{
private readonly Func<string, object> _getLoggerByNameDelegate;
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "LogManager")]
public Log4NetLogProvider()
{
if (!IsLoggerAvailable()) throw new LibLogException("log4net.LogManager not found");
_getLoggerByNameDelegate = GetGetLoggerMethodCall();
}
public static bool ProviderIsAvailableOverride { get; set; } = true;
public override Logger GetLogger(string name)
{
return new Log4NetLogger(_getLoggerByNameDelegate(name)).Log;
}
internal static bool IsLoggerAvailable()
{
return ProviderIsAvailableOverride && GetLogManagerType() != null;
}
protected override OpenNdc GetOpenNdcMethod()
{
var logicalThreadContextType = FindType("log4net.LogicalThreadContext", "log4net");
var stacksProperty = logicalThreadContextType.GetProperty("Stacks");
var logicalThreadContextStacksType = stacksProperty.PropertyType;
var stacksIndexerProperty = logicalThreadContextStacksType.GetProperty("Item");
var stackType = stacksIndexerProperty.PropertyType;
var pushMethod = stackType.GetMethod("Push");
var messageParameter =
Expression.Parameter(typeof(string), "message");
// message => LogicalThreadContext.Stacks.Item["NDC"].Push(message);
var callPushBody =
Expression.Call(
Expression.Property(Expression.Property(null, stacksProperty),
stacksIndexerProperty,
Expression.Constant("NDC")),
pushMethod,
messageParameter);
var result =
Expression.Lambda<OpenNdc>(callPushBody, messageParameter)
.Compile();
return result;
}
protected override OpenMdc GetOpenMdcMethod()
{
var logicalThreadContextType = FindType("log4net.LogicalThreadContext", "log4net");
var propertiesProperty = logicalThreadContextType.GetProperty("Properties");
var logicalThreadContextPropertiesType = propertiesProperty.PropertyType;
var propertiesIndexerProperty = logicalThreadContextPropertiesType.GetProperty("Item");
var removeMethod = logicalThreadContextPropertiesType.GetMethod("Remove");
var keyParam = Expression.Parameter(typeof(string), "key");
var valueParam = Expression.Parameter(typeof(string), "value");
var propertiesExpression = Expression.Property(null, propertiesProperty);
// (key, value) => LogicalThreadContext.Properties.Item[key] = value;
var setProperties =
Expression.Assign(Expression.Property(propertiesExpression, propertiesIndexerProperty, keyParam),
valueParam);
// key => LogicalThreadContext.Properties.Remove(key);
var removeMethodCall = Expression.Call(propertiesExpression, removeMethod, keyParam);
var set = Expression
.Lambda<Action<string, string>>(setProperties, keyParam, valueParam)
.Compile();
var remove = Expression
.Lambda<Action<string>>(removeMethodCall, keyParam)
.Compile();
return (key, value, _) =>
{
set(key, value.ToString());
return new DisposableAction(() => remove(key));
};
}
private static Type GetLogManagerType()
{
return FindType("log4net.LogManager", "log4net");
}
private static Func<string, object> GetGetLoggerMethodCall()
{
var logManagerType = GetLogManagerType();
var log4netAssembly = Assembly.GetAssembly(logManagerType);
var method = logManagerType.GetMethod("GetLogger", typeof(Assembly), typeof(string));
var repositoryAssemblyParam = Expression.Parameter(typeof(Assembly), "repositoryAssembly");
var nameParam = Expression.Parameter(typeof(string), "name");
var methodCall = Expression.Call(null, method, repositoryAssemblyParam, nameParam);
var lambda = Expression
.Lambda<Func<Assembly, string, object>>(methodCall, repositoryAssemblyParam, nameParam).Compile();
return name => lambda(log4netAssembly, name);
}
#if LIBLOG_EXCLUDE_CODE_COVERAGE
[ExcludeFromCodeCoverage]
#endif
internal class Log4NetLogger
{
private static object s_levelAll;
private static object s_levelDebug;
private static object s_levelInfo;
private static object s_levelWarn;
private static object s_levelError;
private static object s_levelFatal;
private static Func<object, object, bool> s_isEnabledForDelegate;
private static Action<object, object> s_logDelegate;
private static Func<object, Type, object, string, Exception, object> s_createLoggingEvent;
private static Action<object, string, object> s_loggingEventPropertySetter;
private static readonly Lazy<bool> Initialized =
new Lazy<bool>(Initialize, LazyThreadSafetyMode.ExecutionAndPublication);
private static Exception s_initializeException;
private readonly object _logger;
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "ILogger")]
internal Log4NetLogger(object logger)
{
_logger = logger.GetType().GetProperty("Logger").GetValue(logger);
}
private static bool Initialize()
{
try
{
var logEventLevelType = FindType("log4net.Core.Level", "log4net");
if (logEventLevelType == null) throw new LibLogException("Type log4net.Core.Level was not found.");
var levelFields = logEventLevelType.GetFields().ToList();
s_levelAll = levelFields.First(x => x.Name == "All").GetValue(null);
s_levelDebug = levelFields.First(x => x.Name == "Debug").GetValue(null);
s_levelInfo = levelFields.First(x => x.Name == "Info").GetValue(null);
s_levelWarn = levelFields.First(x => x.Name == "Warn").GetValue(null);
s_levelError = levelFields.First(x => x.Name == "Error").GetValue(null);
s_levelFatal = levelFields.First(x => x.Name == "Fatal").GetValue(null);
// Func<object, object, bool> isEnabledFor = (logger, level) => { return ((log4net.Core.ILogger)logger).IsEnabled(level); }
var loggerType = FindType("log4net.Core.ILogger", "log4net");
if (loggerType == null) throw new LibLogException("Type log4net.Core.ILogger, was not found.");
var instanceParam = Expression.Parameter(typeof(object));
var instanceCast = Expression.Convert(instanceParam, loggerType);
var levelParam = Expression.Parameter(typeof(object));
var levelCast = Expression.Convert(levelParam, logEventLevelType);
s_isEnabledForDelegate = GetIsEnabledFor(loggerType, logEventLevelType, instanceCast, levelCast,
instanceParam, levelParam);
var loggingEventType = FindType("log4net.Core.LoggingEvent", "log4net");
s_createLoggingEvent = GetCreateLoggingEvent(instanceParam, instanceCast, levelParam, levelCast,
loggingEventType);
s_logDelegate = GetLogDelegate(loggerType, loggingEventType, instanceCast, instanceParam);
s_loggingEventPropertySetter = GetLoggingEventPropertySetter(loggingEventType);
}
catch (Exception ex)
{
s_initializeException = ex;
return false;
}
return true;
}
private static Action<object, object> GetLogDelegate(Type loggerType, Type loggingEventType,
UnaryExpression instanceCast,
ParameterExpression instanceParam)
{
//Action<object, object, string, Exception> Log =
//(logger, callerStackBoundaryDeclaringType, level, message, exception) => { ((ILogger)logger).Log(new LoggingEvent(callerStackBoundaryDeclaringType, logger.Repository, logger.Name, level, message, exception)); }
var writeExceptionMethodInfo = loggerType.GetMethod("Log",
loggingEventType);
var loggingEventParameter =
Expression.Parameter(typeof(object), "loggingEvent");
var loggingEventCasted =
Expression.Convert(loggingEventParameter, loggingEventType);
var writeMethodExp = Expression.Call(
instanceCast,
writeExceptionMethodInfo,
loggingEventCasted);
var logDelegate = Expression.Lambda<Action<object, object>>(
writeMethodExp,
instanceParam,
loggingEventParameter).Compile();
return logDelegate;
}
private static Func<object, Type, object, string, Exception, object> GetCreateLoggingEvent(
ParameterExpression instanceParam, UnaryExpression instanceCast, ParameterExpression levelParam,
UnaryExpression levelCast, Type loggingEventType)
{
var callerStackBoundaryDeclaringTypeParam = Expression.Parameter(typeof(Type));
var messageParam = Expression.Parameter(typeof(string));
var exceptionParam = Expression.Parameter(typeof(Exception));
var repositoryProperty = loggingEventType.GetProperty("Repository");
var levelProperty = loggingEventType.GetProperty("Level");
var loggingEventConstructor =
loggingEventType.GetConstructorPortable(typeof(Type), repositoryProperty.PropertyType,
typeof(string), levelProperty.PropertyType, typeof(object), typeof(Exception));
//Func<object, object, string, Exception, object> Log =
//(logger, callerStackBoundaryDeclaringType, level, message, exception) => new LoggingEvent(callerStackBoundaryDeclaringType, ((ILogger)logger).Repository, ((ILogger)logger).Name, (Level)level, message, exception); }
var newLoggingEventExpression =
Expression.New(loggingEventConstructor,
callerStackBoundaryDeclaringTypeParam,
Expression.Property(instanceCast, "Repository"),
Expression.Property(instanceCast, "Name"),
levelCast,
messageParam,
exceptionParam);
var createLoggingEvent =
Expression.Lambda<Func<object, Type, object, string, Exception, object>>(
newLoggingEventExpression,
instanceParam,
callerStackBoundaryDeclaringTypeParam,
levelParam,
messageParam,
exceptionParam)
.Compile();
return createLoggingEvent;
}
private static Func<object, object, bool> GetIsEnabledFor(Type loggerType, Type logEventLevelType,
UnaryExpression instanceCast,
UnaryExpression levelCast,
ParameterExpression instanceParam,
ParameterExpression levelParam)
{
var isEnabledMethodInfo = loggerType.GetMethod("IsEnabledFor", logEventLevelType);
var isEnabledMethodCall = Expression.Call(instanceCast, isEnabledMethodInfo, levelCast);
var result =
Expression.Lambda<Func<object, object, bool>>(isEnabledMethodCall, instanceParam, levelParam)
.Compile();
return result;
}
private static Action<object, string, object> GetLoggingEventPropertySetter(Type loggingEventType)
{
var loggingEventParameter = Expression.Parameter(typeof(object), "loggingEvent");
var keyParameter = Expression.Parameter(typeof(string), "key");
var valueParameter = Expression.Parameter(typeof(object), "value");
var propertiesProperty = loggingEventType.GetProperty("Properties");
var item = propertiesProperty.PropertyType.GetProperty("Item");
// ((LoggingEvent)loggingEvent).Properties[key] = value;
var body =
Expression.Assign(
Expression.Property(
Expression.Property(Expression.Convert(loggingEventParameter, loggingEventType),
propertiesProperty), item, keyParameter), valueParameter);
var result =
Expression.Lambda<Action<object, string, object>>
(body, loggingEventParameter, keyParameter,
valueParameter)
.Compile();
return result;
}
public bool Log(LogLevel logLevel, Func<string> messageFunc, Exception exception,
params object[] formatParameters)
{
if (!Initialized.Value)
throw new LibLogException(ErrorInitializingProvider, s_initializeException);
if (messageFunc == null) return IsLogLevelEnable(logLevel);
if (!IsLogLevelEnable(logLevel)) return false;
var formattedMessage =
LogMessageFormatter.FormatStructuredMessage(messageFunc(),
formatParameters,
out var patternMatches);
var callerStackBoundaryType = typeof(Log4NetLogger);
// Callsite HACK - Extract the callsite-logger-type from the messageFunc
var methodType = messageFunc.Method.DeclaringType;
if (methodType == typeof(LogExtensions) ||
methodType != null && methodType.DeclaringType == typeof(LogExtensions))
callerStackBoundaryType = typeof(LogExtensions);
else if (methodType == typeof(LoggerExecutionWrapper) ||
methodType != null && methodType.DeclaringType == typeof(LoggerExecutionWrapper))
callerStackBoundaryType = typeof(LoggerExecutionWrapper);
var translatedLevel = TranslateLevel(logLevel);
object loggingEvent = s_createLoggingEvent(_logger, callerStackBoundaryType, translatedLevel,
formattedMessage, exception);
PopulateProperties(loggingEvent, patternMatches, formatParameters);
s_logDelegate(_logger, loggingEvent);
return true;
}
private void PopulateProperties(object loggingEvent, IEnumerable<string> patternMatches,
IEnumerable<object> formatParameters)
{
var enumerable = patternMatches as string[] ?? patternMatches.ToArray();
if (enumerable.Any())
{
var keyToValue =
enumerable.Zip(formatParameters,
(key, value) => new KeyValuePair<string, object>(key, value));
foreach (var keyValuePair in keyToValue)
s_loggingEventPropertySetter(loggingEvent, keyValuePair.Key, keyValuePair.Value);
}
}
private bool IsLogLevelEnable(LogLevel logLevel)
{
var level = TranslateLevel(logLevel);
return s_isEnabledForDelegate(_logger, level);
}
private object TranslateLevel(LogLevel logLevel)
{
switch (logLevel)
{
case LogLevel.Trace:
return s_levelAll;
case LogLevel.Debug:
return s_levelDebug;
case LogLevel.Info:
return s_levelInfo;
case LogLevel.Warn:
return s_levelWarn;
case LogLevel.Error:
return s_levelError;
case LogLevel.Fatal:
return s_levelFatal;
default:
throw new ArgumentOutOfRangeException("logLevel", logLevel, null);
}
}
}
}
}

View file

@ -0,0 +1,96 @@
// <auto-generated/>
// ReSharper disable CheckNamespace
namespace RSTP_DSLink.Logging.LogProviders
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
#if LIBLOG_EXCLUDE_CODE_COVERAGE
using System.Diagnostics.CodeAnalysis;
[ExcludeFromCodeCoverage]
#endif
internal static class LogMessageFormatter
{
private static readonly Regex Pattern = new Regex(@"(?<!{){@?(?<arg>[^ :{}]+)(?<format>:[^}]+)?}",
RegexOptions.Compiled);
/// <summary>
/// Some logging frameworks support structured logging, such as serilog. This will allow you to add names to structured
/// data in a format string:
/// For example: Log("Log message to {user}", user). This only works with serilog, but as the user of LibLog, you don't
/// know if serilog is actually
/// used. So, this class simulates that. it will replace any text in {curly braces} with an index number.
/// "Log {message} to {user}" would turn into => "Log {0} to {1}". Then the format parameters are handled using regular
/// .net string.Format.
/// </summary>
/// <param name="messageBuilder">The message builder.</param>
/// <param name="formatParameters">The format parameters.</param>
/// <returns></returns>
public static Func<string> SimulateStructuredLogging(Func<string> messageBuilder, object[] formatParameters)
{
if (formatParameters == null || formatParameters.Length == 0) return messageBuilder;
return () =>
{
var targetMessage = messageBuilder();
IEnumerable<string> _;
return FormatStructuredMessage(targetMessage, formatParameters, out _);
};
}
private static string ReplaceFirst(string text, string search, string replace)
{
var pos = text.IndexOf(search, StringComparison.Ordinal);
if (pos < 0) return text;
return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
}
public static string FormatStructuredMessage(string targetMessage, object[] formatParameters,
out IEnumerable<string> patternMatches)
{
if (formatParameters == null || formatParameters.Length == 0)
{
patternMatches = Enumerable.Empty<string>();
return targetMessage;
}
List<string> processedArguments = null;
foreach (Match match in Pattern.Matches(targetMessage))
{
var arg = match.Groups["arg"].Value;
int result;
if (!int.TryParse(arg, out result))
{
processedArguments = processedArguments ?? new List<string>(formatParameters.Length);
var argumentIndex = processedArguments.IndexOf(arg);
if (argumentIndex == -1)
{
argumentIndex = processedArguments.Count;
processedArguments.Add(arg);
}
targetMessage = ReplaceFirst(targetMessage, match.Value,
string.Concat("{", argumentIndex.ToString(), match.Groups["format"].Value, "}"));
}
}
patternMatches = processedArguments ?? Enumerable.Empty<string>();
try
{
return string.Format(CultureInfo.InvariantCulture, targetMessage, formatParameters);
}
catch (FormatException ex)
{
throw new FormatException(
"The input string '" + targetMessage + "' could not be formatted using string.Format", ex);
}
}
}
}

View file

@ -0,0 +1,135 @@
// <auto-generated/>
// ReSharper disable CheckNamespace
namespace RSTP_DSLink.Logging.LogProviders
{
using System;
using System.Collections.Generic;
using System.Linq;
#if LIBLOG_EXCLUDE_CODE_COVERAGE
using System.Diagnostics.CodeAnalysis;
#endif
/// <summary>
/// Base class for specific log providers.
/// </summary>
#if LIBLOG_EXCLUDE_CODE_COVERAGE
[ExcludeFromCodeCoverage]
#endif
#if LIBLOG_PUBLIC
public
#else
internal
#endif
abstract class LogProviderBase : ILogProvider
{
private static readonly IDisposable NoopDisposableInstance = new DisposableAction();
private readonly Lazy<OpenMdc> _lazyOpenMdcMethod;
/// <summary>
/// Error message should initializing the log provider fail.
/// </summary>
protected const string ErrorInitializingProvider = "Unable to log due to problem initializing the log provider. See inner exception for details.";
private readonly Lazy<OpenNdc> _lazyOpenNdcMethod;
/// <summary>
/// Initialize an instance of the <see cref="LogProviderBase"/> class by initializing the references
/// to the nested and mapped diagnostics context-obtaining functions.
/// </summary>
protected LogProviderBase()
{
_lazyOpenNdcMethod
= new Lazy<OpenNdc>(GetOpenNdcMethod);
_lazyOpenMdcMethod
= new Lazy<OpenMdc>(GetOpenMdcMethod);
}
/// <summary>
/// Gets the specified named logger.
/// </summary>
/// <param name="name">Name of the logger.</param>
/// <returns>The logger reference.</returns>
public abstract Logger GetLogger(string name);
/// <summary>
/// Opens a nested diagnostics context. Not supported in EntLib logging.
/// </summary>
/// <param name="message">The message to add to the diagnostics context.</param>
/// <returns>A disposable that when disposed removes the message from the context.</returns>
public IDisposable OpenNestedContext(string message)
{
return _lazyOpenNdcMethod.Value(message);
}
/// <summary>
/// Opens a mapped diagnostics context. Not supported in EntLib logging.
/// </summary>
/// <param name="key">A key.</param>
/// <param name="value">A value.</param>
/// <param name="destructure">Determines whether to call the destructor or not.</param>
/// <returns>A disposable that when disposed removes the map from the context.</returns>
public IDisposable OpenMappedContext(string key, object value, bool destructure = false)
{
return _lazyOpenMdcMethod.Value(key, value, destructure);
}
/// <summary>
/// Returns the provider-specific method to open a nested diagnostics context.
/// </summary>
/// <returns>A provider-specific method to open a nested diagnostics context.</returns>
protected virtual OpenNdc GetOpenNdcMethod()
{
return (_) => NoopDisposableInstance;
}
/// <summary>
/// Returns the provider-specific method to open a mapped diagnostics context.
/// </summary>
/// <returns>A provider-specific method to open a mapped diagnostics context.</returns>
protected virtual OpenMdc GetOpenMdcMethod()
{
return (_, __, ___) => NoopDisposableInstance;
}
/// <summary>
/// Delegate defining the signature of the method opening a nested diagnostics context.
/// </summary>
/// <param name="message">The message to add to the diagnostics context.</param>
/// <returns>A disposable that when disposed removes the message from the context.</returns>
protected delegate IDisposable OpenNdc(string message);
/// <summary>
/// Delegate defining the signature of the method opening a mapped diagnostics context.
/// </summary>
/// <param name="key">A key.</param>
/// <param name="value">A value.</param>
/// <param name="destructure">Determines whether to call the destructor or not.</param>
/// <returns>A disposable that when disposed removes the map from the context.</returns>
protected delegate IDisposable OpenMdc(string key, object value, bool destructure);
/// <summary>
/// Finds a type using a type name and assembly name.
/// </summary>
/// <param name="typeName">The name of the type.</param>
/// <param name="assemblyName">The name of the assembly.</param>
/// <returns>The requested type or null if it was not found.</returns>
protected static Type FindType(string typeName, string assemblyName)
{
return FindType(typeName, new[] {assemblyName});
}
/// <summary>
/// Finds a type using a type name and a list of assembly names to search.
/// </summary>
/// <param name="typeName">The name of the type.</param>
/// <param name="assemblyNames">A list of assembly names to search.</param>
/// <returns>The request type or null if it was not found.</returns>
protected static Type FindType(string typeName, IReadOnlyList<string> assemblyNames)
{
return assemblyNames
.Select(assemblyName => Type.GetType($"{typeName}, {assemblyName}"))
.FirstOrDefault(type => type != null) ?? Type.GetType(typeName);
}
}
}

View file

@ -0,0 +1,142 @@
// <auto-generated/>
// ReSharper disable CheckNamespace
namespace RSTP_DSLink.Logging.LogProviders
{
using System;
#if LIBLOG_EXCLUDE_CODE_COVERAGE
using System.Diagnostics.CodeAnalysis;
[ExcludeFromCodeCoverage]
#endif
internal class LoupeLogProvider : LogProviderBase
{
/// <summary>
/// The form of the Loupe Log.Write method we're using
/// </summary>
internal delegate void WriteDelegate(
int severity,
string logSystem,
int skipFrames,
Exception exception,
bool attributeToException,
int writeMode,
string detailsXml,
string category,
string caption,
string description,
params object[] args
);
private readonly WriteDelegate _logWriteDelegate;
private const string LoupeAgentNetCoreDll = "Loupe.Agent.NETCore";
private const string LoupeAgentNetFrameworkDll = "Gibraltar.Agent";
public LoupeLogProvider()
{
if (!IsLoggerAvailable()) throw new LibLogException("Gibraltar.Agent.Log (Loupe) not found");
_logWriteDelegate = GetLogWriteDelegate();
}
/// <summary>
/// Gets or sets a value indicating whether [provider is available override]. Used in tests.
/// </summary>
/// <value>
/// <c>true</c> if [provider is available override]; otherwise, <c>false</c>.
/// </value>
public static bool ProviderIsAvailableOverride { get; set; } = true;
public override Logger GetLogger(string name)
{
return new LoupeLogger(name, _logWriteDelegate).Log;
}
public static bool IsLoggerAvailable()
{
return ProviderIsAvailableOverride && GetLogManagerType() != null;
}
private static Type GetTypeFromCoreOrFrameworkDll(string typeName)
{
return FindType(typeName, new[] {LoupeAgentNetCoreDll, LoupeAgentNetFrameworkDll});
}
private static Type GetLogManagerType()
{
return GetTypeFromCoreOrFrameworkDll("Gibraltar.Agent.Log");
}
private static WriteDelegate GetLogWriteDelegate()
{
var logManagerType = GetLogManagerType();
var logMessageSeverityType = GetTypeFromCoreOrFrameworkDll("Gibraltar.Agent.LogMessageSeverity");
var logWriteModeType = GetTypeFromCoreOrFrameworkDll("Gibraltar.Agent.LogWriteMode");
var method = logManagerType.GetMethod(
"Write",
logMessageSeverityType, typeof(string), typeof(int), typeof(Exception), typeof(bool),
logWriteModeType, typeof(string), typeof(string), typeof(string), typeof(string), typeof(object[]));
var callDelegate = (WriteDelegate) method.CreateDelegate(typeof(WriteDelegate));
return callDelegate;
}
#if LIBLOG_EXCLUDE_CODE_COVERAGE
[ExcludeFromCodeCoverage]
#endif
internal class LoupeLogger
{
private const string LogSystem = "LibLog";
private readonly string _category;
private readonly WriteDelegate _logWriteDelegate;
private readonly int _skipLevel;
internal LoupeLogger(string category, WriteDelegate logWriteDelegate)
{
_category = category;
_logWriteDelegate = logWriteDelegate;
#if DEBUG
_skipLevel = 2;
#else
_skipLevel = 1;
#endif
}
public bool Log(LogLevel logLevel, Func<string> messageFunc, Exception exception,
params object[] formatParameters)
{
if (messageFunc == null) return true;
messageFunc = LogMessageFormatter.SimulateStructuredLogging(messageFunc, formatParameters);
_logWriteDelegate(ToLogMessageSeverity(logLevel), LogSystem, _skipLevel, exception, true, 0, null,
_category, null, messageFunc.Invoke());
return true;
}
private static int ToLogMessageSeverity(LogLevel logLevel)
{
switch (logLevel)
{
case LogLevel.Trace:
return TraceEventTypeValues.Verbose;
case LogLevel.Debug:
return TraceEventTypeValues.Verbose;
case LogLevel.Info:
return TraceEventTypeValues.Information;
case LogLevel.Warn:
return TraceEventTypeValues.Warning;
case LogLevel.Error:
return TraceEventTypeValues.Error;
case LogLevel.Fatal:
return TraceEventTypeValues.Critical;
default:
throw new ArgumentOutOfRangeException(nameof(logLevel));
}
}
}
}
}

View file

@ -0,0 +1,539 @@
// <auto-generated/>
// ReSharper disable CheckNamespace
namespace RSTP_DSLink.Logging.LogProviders
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Linq.Expressions;
#if LIBLOG_EXCLUDE_CODE_COVERAGE
[ExcludeFromCodeCoverage]
#endif
internal class NLogLogProvider : LogProviderBase
{
private readonly Func<string, object> _getLoggerByNameDelegate;
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "LogManager")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "NLog")]
public NLogLogProvider()
{
if (!IsLoggerAvailable()) throw new LibLogException("NLog.LogManager not found");
_getLoggerByNameDelegate = GetGetLoggerMethodCall();
}
static NLogLogProvider()
{
ProviderIsAvailableOverride = true;
}
public static bool ProviderIsAvailableOverride { get; set; }
public override Logger GetLogger(string name)
{
return new NLogLogger(_getLoggerByNameDelegate(name)).Log;
}
public static bool IsLoggerAvailable()
{
return ProviderIsAvailableOverride && GetLogManagerType() != null;
}
protected override OpenNdc GetOpenNdcMethod()
{
var messageParam = Expression.Parameter(typeof(string), "message");
var ndlcContextType = FindType("NLog.NestedDiagnosticsLogicalContext", "NLog");
if (ndlcContextType != null)
{
var pushObjectMethod = ndlcContextType.GetMethod("PushObject", typeof(object));
if (pushObjectMethod != null)
{
// NLog 4.6 introduces PushObject with correct handling of logical callcontext (NDLC)
var pushObjectMethodCall = Expression.Call(null, pushObjectMethod, messageParam);
return Expression.Lambda<OpenNdc>(pushObjectMethodCall, messageParam).Compile();
}
}
var ndcContextType = FindType("NLog.NestedDiagnosticsContext", "NLog");
var pushMethod = ndcContextType.GetMethod("Push", typeof(string));
var pushMethodCall = Expression.Call(null, pushMethod, messageParam);
return Expression.Lambda<OpenNdc>(pushMethodCall, messageParam).Compile();
}
protected override OpenMdc GetOpenMdcMethod()
{
var keyParam = Expression.Parameter(typeof(string), "key");
var ndlcContextType = FindType("NLog.NestedDiagnosticsLogicalContext", "NLog");
if (ndlcContextType != null)
{
var pushObjectMethod = ndlcContextType.GetMethod("PushObject", typeof(object));
if (pushObjectMethod != null)
{
// NLog 4.6 introduces SetScoped with correct handling of logical callcontext (MDLC)
var mdlcContextType = FindType("NLog.MappedDiagnosticsLogicalContext", "NLog");
if (mdlcContextType != null)
{
var setScopedMethod = mdlcContextType.GetMethod("SetScoped", typeof(string), typeof(object));
if (setScopedMethod != null)
{
var valueObjParam = Expression.Parameter(typeof(object), "value");
var setScopedMethodCall = Expression.Call(null, setScopedMethod, keyParam, valueObjParam);
var setMethodLambda = Expression.Lambda<Func<string, object, IDisposable>>(setScopedMethodCall, keyParam, valueObjParam).Compile();
return (key, value, _) => setMethodLambda(key, value);
}
}
}
}
var mdcContextType = FindType("NLog.MappedDiagnosticsContext", "NLog");
var setMethod = mdcContextType.GetMethod("Set", typeof(string), typeof(string));
var removeMethod = mdcContextType.GetMethod("Remove", typeof(string));
var valueParam = Expression.Parameter(typeof(string), "value");
var setMethodCall = Expression.Call(null, setMethod, keyParam, valueParam);
var removeMethodCall = Expression.Call(null, removeMethod, keyParam);
var set = Expression
.Lambda<Action<string, string>>(setMethodCall, keyParam, valueParam)
.Compile();
var remove = Expression
.Lambda<Action<string>>(removeMethodCall, keyParam)
.Compile();
return (key, value, _) =>
{
set(key, value.ToString());
return new DisposableAction(() => remove(key));
};
}
private static Type GetLogManagerType()
{
return FindType("NLog.LogManager", "NLog");
}
private static Func<string, object> GetGetLoggerMethodCall()
{
var logManagerType = GetLogManagerType();
var method = logManagerType.GetMethod("GetLogger", typeof(string));
var nameParam = Expression.Parameter(typeof(string), "name");
var methodCall = Expression.Call(null, method, nameParam);
return Expression.Lambda<Func<string, object>>(methodCall, nameParam).Compile();
}
#if LIBLOG_EXCLUDE_CODE_COVERAGE
[ExcludeFromCodeCoverage]
#endif
internal class NLogLogger
{
private static Func<string, object, string, object[], Exception, object> s_logEventInfoFact;
private static object s_levelTrace;
private static object s_levelDebug;
private static object s_levelInfo;
private static object s_levelWarn;
private static object s_levelError;
private static object s_levelFatal;
private static bool s_structuredLoggingEnabled;
private static readonly Lazy<bool> Initialized = new Lazy<bool>(Initialize);
private static Exception s_initializeException;
delegate string LoggerNameDelegate(object logger);
delegate void LogEventDelegate(object logger, Type wrapperType, object logEvent);
delegate bool IsEnabledDelegate(object logger);
delegate void LogDelegate(object logger, string message);
delegate void LogExceptionDelegate(object logger, string message, Exception exception);
private static LoggerNameDelegate s_loggerNameDelegate;
private static LogEventDelegate s_logEventDelegate;
private static IsEnabledDelegate s_isTraceEnabledDelegate;
private static IsEnabledDelegate s_isDebugEnabledDelegate;
private static IsEnabledDelegate s_isInfoEnabledDelegate;
private static IsEnabledDelegate s_isWarnEnabledDelegate;
private static IsEnabledDelegate s_isErrorEnabledDelegate;
private static IsEnabledDelegate s_isFatalEnabledDelegate;
private static LogDelegate s_traceDelegate;
private static LogDelegate s_debugDelegate;
private static LogDelegate s_infoDelegate;
private static LogDelegate s_warnDelegate;
private static LogDelegate s_errorDelegate;
private static LogDelegate s_fatalDelegate;
private static LogExceptionDelegate s_traceExceptionDelegate;
private static LogExceptionDelegate s_debugExceptionDelegate;
private static LogExceptionDelegate s_infoExceptionDelegate;
private static LogExceptionDelegate s_warnExceptionDelegate;
private static LogExceptionDelegate s_errorExceptionDelegate;
private static LogExceptionDelegate s_fatalExceptionDelegate;
private readonly object _logger;
internal NLogLogger(object logger)
{
_logger = logger;
}
private static bool Initialize()
{
try
{
var logEventLevelType = FindType("NLog.LogLevel", "NLog");
if (logEventLevelType == null) throw new LibLogException("Type NLog.LogLevel was not found.");
var levelFields = logEventLevelType.GetFields().ToList();
s_levelTrace = levelFields.First(x => x.Name == "Trace").GetValue(null);
s_levelDebug = levelFields.First(x => x.Name == "Debug").GetValue(null);
s_levelInfo = levelFields.First(x => x.Name == "Info").GetValue(null);
s_levelWarn = levelFields.First(x => x.Name == "Warn").GetValue(null);
s_levelError = levelFields.First(x => x.Name == "Error").GetValue(null);
s_levelFatal = levelFields.First(x => x.Name == "Fatal").GetValue(null);
var logEventInfoType = FindType("NLog.LogEventInfo", "NLog");
if (logEventInfoType == null) throw new LibLogException("Type NLog.LogEventInfo was not found.");
var loggingEventConstructor =
logEventInfoType.GetConstructorPortable(logEventLevelType, typeof(string),
typeof(IFormatProvider), typeof(string), typeof(object[]), typeof(Exception));
var loggerNameParam = Expression.Parameter(typeof(string));
var levelParam = Expression.Parameter(typeof(object));
var messageParam = Expression.Parameter(typeof(string));
var messageArgsParam = Expression.Parameter(typeof(object[]));
var exceptionParam = Expression.Parameter(typeof(Exception));
var levelCast = Expression.Convert(levelParam, logEventLevelType);
var newLoggingEventExpression =
Expression.New(loggingEventConstructor,
levelCast,
loggerNameParam,
Expression.Constant(null, typeof(IFormatProvider)),
messageParam,
messageArgsParam,
exceptionParam
);
s_logEventInfoFact = Expression.Lambda<Func<string, object, string, object[], Exception, object>>(
newLoggingEventExpression,
loggerNameParam, levelParam, messageParam, messageArgsParam, exceptionParam).Compile();
var loggerType = FindType("NLog.Logger", "NLog");
s_loggerNameDelegate = GetLoggerNameDelegate(loggerType);
s_logEventDelegate = GetLogEventDelegate(loggerType, logEventInfoType);
s_isTraceEnabledDelegate = GetIsEnabledDelegate(loggerType, "IsTraceEnabled");
s_isDebugEnabledDelegate = GetIsEnabledDelegate(loggerType, "IsDebugEnabled");
s_isInfoEnabledDelegate = GetIsEnabledDelegate(loggerType, "IsInfoEnabled");
s_isWarnEnabledDelegate = GetIsEnabledDelegate(loggerType, "IsWarnEnabled");
s_isErrorEnabledDelegate = GetIsEnabledDelegate(loggerType, "IsErrorEnabled");
s_isFatalEnabledDelegate = GetIsEnabledDelegate(loggerType, "IsFatalEnabled");
s_traceDelegate = GetLogDelegate(loggerType, "Trace");
s_debugDelegate = GetLogDelegate(loggerType, "Debug");
s_infoDelegate = GetLogDelegate(loggerType, "Info");
s_warnDelegate = GetLogDelegate(loggerType, "Warn");
s_errorDelegate = GetLogDelegate(loggerType, "Error");
s_fatalDelegate = GetLogDelegate(loggerType, "Fatal");
s_traceExceptionDelegate = GetLogExceptionDelegate(loggerType, "TraceException");
s_debugExceptionDelegate = GetLogExceptionDelegate(loggerType, "DebugException");
s_infoExceptionDelegate = GetLogExceptionDelegate(loggerType, "InfoException");
s_warnExceptionDelegate = GetLogExceptionDelegate(loggerType, "WarnException");
s_errorExceptionDelegate = GetLogExceptionDelegate(loggerType, "ErrorException");
s_fatalExceptionDelegate = GetLogExceptionDelegate(loggerType, "FatalException");
s_structuredLoggingEnabled = IsStructuredLoggingEnabled();
}
catch (Exception ex)
{
s_initializeException = ex;
return false;
}
return true;
}
private static IsEnabledDelegate GetIsEnabledDelegate(Type loggerType, string propertyName)
{
var isEnabledPropertyInfo = loggerType.GetProperty(propertyName);
var instanceParam = Expression.Parameter(typeof(object));
var instanceCast = Expression.Convert(instanceParam, loggerType);
var propertyCall = Expression.Property(instanceCast, isEnabledPropertyInfo);
return Expression.Lambda<IsEnabledDelegate>(propertyCall, instanceParam).Compile();
}
private static LoggerNameDelegate GetLoggerNameDelegate(Type loggerType)
{
var isEnabledPropertyInfo = loggerType.GetProperty("Name");
var instanceParam = Expression.Parameter(typeof(object));
var instanceCast = Expression.Convert(instanceParam, loggerType);
var propertyCall = Expression.Property(instanceCast, isEnabledPropertyInfo);
return Expression.Lambda<LoggerNameDelegate>(propertyCall, instanceParam).Compile();
}
private static LogDelegate GetLogDelegate(Type loggerType, string name)
{
var logMethodInfo = loggerType.GetMethod(name, new Type[] { typeof(string) });
var instanceParam = Expression.Parameter(typeof(object));
var instanceCast = Expression.Convert(instanceParam, loggerType);
var messageParam = Expression.Parameter(typeof(string));
var logCall = Expression.Call(instanceCast, logMethodInfo, messageParam);
return Expression.Lambda<LogDelegate>(logCall, instanceParam, messageParam).Compile();
}
private static LogEventDelegate GetLogEventDelegate(Type loggerType, Type logEventType)
{
var logMethodInfo = loggerType.GetMethod("Log", new Type[] { typeof(Type), logEventType });
var instanceParam = Expression.Parameter(typeof(object));
var instanceCast = Expression.Convert(instanceParam, loggerType);
var loggerTypeParam = Expression.Parameter(typeof(Type));
var logEventParam = Expression.Parameter(typeof(object));
var logEventCast = Expression.Convert(logEventParam, logEventType);
var logCall = Expression.Call(instanceCast, logMethodInfo, loggerTypeParam, logEventCast);
return Expression.Lambda<LogEventDelegate>(logCall, instanceParam, loggerTypeParam, logEventParam).Compile();
}
private static LogExceptionDelegate GetLogExceptionDelegate(Type loggerType, string name)
{
var logMethodInfo = loggerType.GetMethod(name, new Type[] { typeof(string), typeof(Exception) });
var instanceParam = Expression.Parameter(typeof(object));
var instanceCast = Expression.Convert(instanceParam, loggerType);
var messageParam = Expression.Parameter(typeof(string));
var exceptionParam = Expression.Parameter(typeof(Exception));
var logCall = Expression.Call(instanceCast, logMethodInfo, messageParam, exceptionParam);
return Expression.Lambda<LogExceptionDelegate>(logCall, instanceParam, messageParam, exceptionParam).Compile();
}
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
public bool Log(LogLevel logLevel, Func<string> messageFunc, Exception exception,
params object[] formatParameters)
{
if (!Initialized.Value)
throw new LibLogException(ErrorInitializingProvider, s_initializeException);
if (messageFunc == null) return IsLogLevelEnable(logLevel);
if (s_logEventInfoFact != null)
{
if (IsLogLevelEnable(logLevel))
{
var formatMessage = messageFunc();
if (!s_structuredLoggingEnabled)
{
IEnumerable<string> _;
formatMessage =
LogMessageFormatter.FormatStructuredMessage(formatMessage,
formatParameters,
out _);
formatParameters = null; // Has been formatted, no need for parameters
}
var callsiteLoggerType = typeof(NLogLogger);
// Callsite HACK - Extract the callsite-logger-type from the messageFunc
var methodType = messageFunc.Method.DeclaringType;
if (methodType == typeof(LogExtensions) ||
methodType != null && methodType.DeclaringType == typeof(LogExtensions))
callsiteLoggerType = typeof(LogExtensions);
else if (methodType == typeof(LoggerExecutionWrapper) || methodType != null &&
methodType.DeclaringType == typeof(LoggerExecutionWrapper))
callsiteLoggerType = typeof(LoggerExecutionWrapper);
var nlogLevel = TranslateLevel(logLevel);
var nlogEvent = s_logEventInfoFact(s_loggerNameDelegate(_logger), nlogLevel, formatMessage, formatParameters,
exception);
s_logEventDelegate(_logger, callsiteLoggerType, nlogEvent);
return true;
}
return false;
}
messageFunc = LogMessageFormatter.SimulateStructuredLogging(messageFunc, formatParameters);
if (exception != null) return LogException(logLevel, messageFunc, exception);
switch (logLevel)
{
case LogLevel.Debug:
if (s_isDebugEnabledDelegate(_logger))
{
s_debugDelegate(_logger, messageFunc());
return true;
}
break;
case LogLevel.Info:
if (s_isInfoEnabledDelegate(_logger))
{
s_infoDelegate(_logger, messageFunc());
return true;
}
break;
case LogLevel.Warn:
if (s_isWarnEnabledDelegate(_logger))
{
s_warnDelegate(_logger, messageFunc());
return true;
}
break;
case LogLevel.Error:
if (s_isErrorEnabledDelegate(_logger))
{
s_errorDelegate(_logger, messageFunc());
return true;
}
break;
case LogLevel.Fatal:
if (s_isFatalEnabledDelegate(_logger))
{
s_fatalDelegate(_logger, messageFunc());
return true;
}
break;
default:
if (s_isTraceEnabledDelegate(_logger))
{
s_traceDelegate(_logger, messageFunc());
return true;
}
break;
}
return false;
}
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
private bool LogException(LogLevel logLevel, Func<string> messageFunc, Exception exception)
{
switch (logLevel)
{
case LogLevel.Debug:
if (s_isDebugEnabledDelegate(_logger))
{
s_debugExceptionDelegate(_logger, messageFunc(), exception);
return true;
}
break;
case LogLevel.Info:
if (s_isInfoEnabledDelegate(_logger))
{
s_infoExceptionDelegate(_logger, messageFunc(), exception);
return true;
}
break;
case LogLevel.Warn:
if (s_isWarnEnabledDelegate(_logger))
{
s_warnExceptionDelegate(_logger, messageFunc(), exception);
return true;
}
break;
case LogLevel.Error:
if (s_isErrorEnabledDelegate(_logger))
{
s_errorExceptionDelegate(_logger, messageFunc(), exception);
return true;
}
break;
case LogLevel.Fatal:
if (s_isFatalEnabledDelegate(_logger))
{
s_fatalExceptionDelegate(_logger, messageFunc(), exception);
return true;
}
break;
default:
if (s_isTraceEnabledDelegate(_logger))
{
s_traceExceptionDelegate(_logger, messageFunc(), exception);
return true;
}
break;
}
return false;
}
private bool IsLogLevelEnable(LogLevel logLevel)
{
switch (logLevel)
{
case LogLevel.Debug:
return s_isDebugEnabledDelegate(_logger);
case LogLevel.Info:
return s_isInfoEnabledDelegate(_logger);
case LogLevel.Warn:
return s_isWarnEnabledDelegate(_logger);
case LogLevel.Error:
return s_isErrorEnabledDelegate(_logger);
case LogLevel.Fatal:
return s_isFatalEnabledDelegate(_logger);
default:
return s_isTraceEnabledDelegate(_logger);
}
}
private object TranslateLevel(LogLevel logLevel)
{
switch (logLevel)
{
case LogLevel.Trace:
return s_levelTrace;
case LogLevel.Debug:
return s_levelDebug;
case LogLevel.Info:
return s_levelInfo;
case LogLevel.Warn:
return s_levelWarn;
case LogLevel.Error:
return s_levelError;
case LogLevel.Fatal:
return s_levelFatal;
default:
throw new ArgumentOutOfRangeException(nameof(logLevel), logLevel, null);
}
}
private static bool IsStructuredLoggingEnabled()
{
var configFactoryType = FindType("NLog.Config.ConfigurationItemFactory", "NLog");
if (configFactoryType != null)
{
var parseMessagesProperty = configFactoryType.GetProperty("ParseMessageTemplates");
if (parseMessagesProperty != null)
{
var defaultProperty = configFactoryType.GetProperty("Default");
if (defaultProperty != null)
{
var configFactoryDefault = defaultProperty.GetValue(null, null);
if (configFactoryDefault != null)
{
var parseMessageTemplates =
parseMessagesProperty.GetValue(configFactoryDefault, null) as bool?;
if (parseMessageTemplates != false) return true;
}
}
}
}
return false;
}
}
}
}

View file

@ -0,0 +1,246 @@
// <auto-generated/>
// ReSharper disable CheckNamespace
namespace RSTP_DSLink.Logging.LogProviders
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
#if LIBLOG_EXCLUDE_CODE_COVERAGE
[ExcludeFromCodeCoverage]
#endif
internal class SerilogLogProvider : LogProviderBase
{
private readonly Func<string, object> _getLoggerByNameDelegate;
private static Func<string, object, bool, IDisposable> s_pushProperty;
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "Serilog")]
public SerilogLogProvider()
{
if (!IsLoggerAvailable()) throw new LibLogException("Serilog.Log not found");
_getLoggerByNameDelegate = GetForContextMethodCall();
s_pushProperty = GetPushProperty();
}
public static bool ProviderIsAvailableOverride { get; set; } = true;
public override Logger GetLogger(string name)
=> new SerilogLogger(_getLoggerByNameDelegate(name)).Log;
internal static bool IsLoggerAvailable()
=> ProviderIsAvailableOverride && GetLogManagerType() != null;
protected override OpenNdc GetOpenNdcMethod()
=> message => s_pushProperty("NDC", message, false);
protected override OpenMdc GetOpenMdcMethod()
=> (key, value, destructure) => s_pushProperty(key, value, destructure);
private static Func<string, object, bool, IDisposable> GetPushProperty()
{
var ndcContextType = FindType("Serilog.Context.LogContext", new[] {"Serilog", "Serilog.FullNetFx"});
var pushPropertyMethod = ndcContextType.GetMethod(
"PushProperty",
typeof(string),
typeof(object),
typeof(bool));
var nameParam = Expression.Parameter(typeof(string), "name");
var valueParam = Expression.Parameter(typeof(object), "value");
var destructureObjectParam = Expression.Parameter(typeof(bool), "destructureObjects");
var pushPropertyMethodCall = Expression
.Call(null, pushPropertyMethod, nameParam, valueParam, destructureObjectParam);
var pushProperty = Expression
.Lambda<Func<string, object, bool, IDisposable>>(
pushPropertyMethodCall,
nameParam,
valueParam,
destructureObjectParam)
.Compile();
return (key, value, destructure) => pushProperty(key, value, destructure);
}
private static Type GetLogManagerType()
=> FindType("Serilog.Log", "Serilog");
private static Func<string, object> GetForContextMethodCall()
{
var logManagerType = GetLogManagerType();
var method = logManagerType.GetMethod("ForContext", typeof(string), typeof(object), typeof(bool));
var propertyNameParam = Expression.Parameter(typeof(string), "propertyName");
var valueParam = Expression.Parameter(typeof(object), "value");
var destructureObjectsParam = Expression.Parameter(typeof(bool), "destructureObjects");
var methodCall = Expression.Call(null, method, new Expression[]
{
propertyNameParam,
valueParam,
destructureObjectsParam
});
var func = Expression.Lambda<Func<string, object, bool, object>>(
methodCall,
propertyNameParam,
valueParam,
destructureObjectsParam)
.Compile();
return name => func("SourceContext", name, false);
}
#if LIBLOG_EXCLUDE_CODE_COVERAGE
[ExcludeFromCodeCoverage]
#endif
internal class SerilogLogger
{
private static object s_debugLevel;
private static object s_errorLevel;
private static object s_fatalLevel;
private static object s_informationLevel;
private static object s_verboseLevel;
private static object s_warningLevel;
private static Func<object, object, bool> s_isEnabled;
private static Action<object, object, string, object[]> s_write;
private static Action<object, object, Exception, string, object[]> s_writeException;
private static readonly Lazy<bool> Initialized = new Lazy<bool>(Initialize);
private static Exception s_initializeException;
private readonly object _logger;
internal SerilogLogger(object logger)
{
_logger = logger;
}
[SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "ILogger")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId =
"LogEventLevel")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "Serilog")]
private static bool Initialize()
{
try
{
var logEventLevelType = FindType("Serilog.Events.LogEventLevel", "Serilog");
if (logEventLevelType == null)
throw new LibLogException("Type Serilog.Events.LogEventLevel was not found.");
s_debugLevel = Enum.Parse(logEventLevelType, "Debug", false);
s_errorLevel = Enum.Parse(logEventLevelType, "Error", false);
s_fatalLevel = Enum.Parse(logEventLevelType, "Fatal", false);
s_informationLevel = Enum.Parse(logEventLevelType, "Information", false);
s_verboseLevel = Enum.Parse(logEventLevelType, "Verbose", false);
s_warningLevel = Enum.Parse(logEventLevelType, "Warning", false);
// Func<object, object, bool> isEnabled = (logger, level) => { return ((SeriLog.ILogger)logger).IsEnabled(level); }
var loggerType = FindType("Serilog.ILogger", "Serilog");
if (loggerType == null) throw new LibLogException("Type Serilog.ILogger was not found.");
var isEnabledMethodInfo = loggerType.GetMethod("IsEnabled", logEventLevelType);
var instanceParam = Expression.Parameter(typeof(object));
var instanceCast = Expression.Convert(instanceParam, loggerType);
var levelParam = Expression.Parameter(typeof(object));
var levelCast = Expression.Convert(levelParam, logEventLevelType);
var isEnabledMethodCall = Expression.Call(instanceCast, isEnabledMethodInfo, levelCast);
s_isEnabled = Expression
.Lambda<Func<object, object, bool>>(isEnabledMethodCall, instanceParam, levelParam).Compile();
// Action<object, object, string> Write =
// (logger, level, message, params) => { ((SeriLog.ILoggerILogger)logger).Write(level, message, params); }
var writeMethodInfo =
loggerType.GetMethod("Write", logEventLevelType, typeof(string), typeof(object[]));
var messageParam = Expression.Parameter(typeof(string));
var propertyValuesParam = Expression.Parameter(typeof(object[]));
var writeMethodExp = Expression.Call(
instanceCast,
writeMethodInfo,
levelCast,
messageParam,
propertyValuesParam);
var expression = Expression.Lambda<Action<object, object, string, object[]>>(
writeMethodExp,
instanceParam,
levelParam,
messageParam,
propertyValuesParam);
s_write = expression.Compile();
// Action<object, object, string, Exception> WriteException =
// (logger, level, exception, message) => { ((ILogger)logger).Write(level, exception, message, new object[]); }
var writeExceptionMethodInfo = loggerType.GetMethod("Write",
logEventLevelType,
typeof(Exception),
typeof(string),
typeof(object[]));
var exceptionParam = Expression.Parameter(typeof(Exception));
writeMethodExp = Expression.Call(
instanceCast,
writeExceptionMethodInfo,
levelCast,
exceptionParam,
messageParam,
propertyValuesParam);
s_writeException = Expression.Lambda<Action<object, object, Exception, string, object[]>>(
writeMethodExp,
instanceParam,
levelParam,
exceptionParam,
messageParam,
propertyValuesParam).Compile();
}
catch (Exception ex)
{
s_initializeException = ex;
return false;
}
return true;
}
public bool Log(LogLevel logLevel, Func<string> messageFunc, Exception exception,
params object[] formatParameters)
{
if (!Initialized.Value)
throw new LibLogException(ErrorInitializingProvider, s_initializeException);
var translatedLevel = TranslateLevel(logLevel);
if (messageFunc == null) return s_isEnabled(_logger, translatedLevel);
if (!s_isEnabled(_logger, translatedLevel)) return false;
if (exception != null)
LogException(translatedLevel, messageFunc, exception, formatParameters);
else
LogMessage(translatedLevel, messageFunc, formatParameters);
return true;
}
private void LogMessage(object translatedLevel, Func<string> messageFunc, object[] formatParameters)
{
s_write(_logger, translatedLevel, messageFunc(), formatParameters);
}
private void LogException(object logLevel, Func<string> messageFunc, Exception exception,
object[] formatParams)
{
s_writeException(_logger, logLevel, exception, messageFunc(), formatParams);
}
private static object TranslateLevel(LogLevel logLevel)
{
switch (logLevel)
{
case LogLevel.Fatal:
return s_fatalLevel;
case LogLevel.Error:
return s_errorLevel;
case LogLevel.Warn:
return s_warningLevel;
case LogLevel.Info:
return s_informationLevel;
case LogLevel.Trace:
return s_verboseLevel;
default:
return s_debugLevel;
}
}
}
}
}

View file

@ -0,0 +1,33 @@
// <auto-generated/>
// ReSharper disable CheckNamespace
namespace RSTP_DSLink.Logging.LogProviders
{
using System;
using System.Diagnostics.CodeAnalysis;
#if LIBLOG_EXCLUDE_CODE_COVERAGE
[ExcludeFromCodeCoverage]
#endif
internal static class TraceEventTypeValues
{
internal static readonly Type Type;
internal static readonly int Verbose;
internal static readonly int Information;
internal static readonly int Warning;
internal static readonly int Error;
internal static readonly int Critical;
[SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")]
static TraceEventTypeValues()
{
var assembly = typeof(Uri).Assembly;
Type = assembly.GetType("System.Diagnostics.TraceEventType");
if (Type == null) return;
Verbose = (int) Enum.Parse(Type, "Verbose", false);
Information = (int) Enum.Parse(Type, "Information", false);
Warning = (int) Enum.Parse(Type, "Warning", false);
Error = (int) Enum.Parse(Type, "Error", false);
Critical = (int) Enum.Parse(Type, "Critical", false);
}
}
}

View file

@ -0,0 +1,25 @@
// <auto-generated/>
// ReSharper disable CheckNamespace
namespace RSTP_DSLink.Logging.LogProviders
{
using System;
using System.Reflection;
#if LIBLOG_EXCLUDE_CODE_COVERAGE
using System.Diagnostics.CodeAnalysis;
[ExcludeFromCodeCoverage]
#endif
internal static class TypeExtensions
{
internal static ConstructorInfo GetConstructorPortable(this Type type, params Type[] types)
{
return type.GetConstructor(types);
}
internal static MethodInfo GetMethod(this Type type, string name, params Type[] types)
{
return type.GetMethod(name, types);
}
}
}

View file

@ -0,0 +1,21 @@
// <auto-generated/>
// ReSharper disable CheckNamespace
namespace RSTP_DSLink.Logging
{
using System;
#if !LIBLOG_PROVIDERS_ONLY || LIBLOG_PUBLIC
/// <summary>
/// Logger delegate.
/// </summary>
/// <param name="logLevel">The log level</param>
/// <param name="messageFunc">The message function</param>
/// <param name="exception">The exception</param>
/// <param name="formatParameters">The format parameters</param>
/// <returns>A boolean.</returns>
public
#else
internal
#endif
delegate bool Logger(LogLevel logLevel, Func<string> messageFunc, Exception exception = null, params object[] formatParameters);
}

View file

@ -0,0 +1,85 @@
// <auto-generated/>
// ReSharper disable CheckNamespace
namespace RSTP_DSLink.Logging
{
using System;
using System.Diagnostics.CodeAnalysis;
#if LIBLOG_EXCLUDE_CODE_COVERAGE
[ExcludeFromCodeCoverage]
#endif
internal class LoggerExecutionWrapper : ILog
{
internal const string FailedToGenerateLogMessage = "Failed to generate log message";
private readonly ICallSiteExtension _callsiteLogger;
private readonly Func<bool> _getIsDisabled;
private Func<string> _lastExtensionMethod;
internal LoggerExecutionWrapper(Logger logger, Func<bool> getIsDisabled = null)
{
WrappedLogger = logger;
_callsiteLogger = new CallSiteExtension();
_getIsDisabled = getIsDisabled ?? (() => false);
}
internal Logger WrappedLogger { get; }
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public bool Log(LogLevel logLevel, Func<string> messageFunc, Exception exception = null,
params object[] formatParameters)
{
if (_getIsDisabled()) return false;
if (messageFunc == null) return WrappedLogger(logLevel, null, null, LogExtensions.EmptyParams);
// Callsite HACK - Using the messageFunc to provide the callsite-logger-type
var lastExtensionMethod = _lastExtensionMethod;
if (lastExtensionMethod == null || !lastExtensionMethod.Equals(messageFunc))
{
// Callsite HACK - Cache the last validated messageFunc as Equals is faster than type-check
lastExtensionMethod = null;
var methodType = messageFunc.Method.DeclaringType;
if (methodType == typeof(LogExtensions) ||
methodType != null && methodType.DeclaringType == typeof(LogExtensions))
lastExtensionMethod = messageFunc;
}
if (lastExtensionMethod != null)
{
// Callsite HACK - LogExtensions has called virtual ILog interface method to get here, callsite-stack is good
_lastExtensionMethod = lastExtensionMethod;
return WrappedLogger(logLevel, LogExtensions.WrapLogSafeInternal(this, messageFunc), exception,
formatParameters);
}
var WrappedMessageFunc = new Func<string>(() =>
{
try
{
return messageFunc();
}
catch (Exception ex)
{
WrappedLogger(LogLevel.Error, () => FailedToGenerateLogMessage, ex);
}
return null;
});
// Callsite HACK - Need to ensure proper callsite stack without inlining, so calling the logger within a virtual interface method
return _callsiteLogger.Log(WrappedLogger, logLevel, WrappedMessageFunc, exception, formatParameters);
}
private interface ICallSiteExtension
{
bool Log(Logger logger, LogLevel logLevel, Func<string> messageFunc, Exception exception, object[] formatParameters);
}
private class CallSiteExtension : ICallSiteExtension
{
bool ICallSiteExtension.Log(Logger logger, LogLevel logLevel, Func<string> messageFunc, Exception exception, object[] formatParameters)
{
return logger(logLevel, messageFunc, exception, formatParameters);
}
}
}
}

View file

@ -11,12 +11,12 @@
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("DSLink_Test")]
[assembly: System.Reflection.AssemblyCompanyAttribute("RSTP_DSLink")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("DSLink_Test")]
[assembly: System.Reflection.AssemblyTitleAttribute("DSLink_Test")]
[assembly: System.Reflection.AssemblyProductAttribute("RSTP_DSLink")]
[assembly: System.Reflection.AssemblyTitleAttribute("RSTP_DSLink")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Généré par la classe MSBuild WriteCodeFragment.

View file

@ -0,0 +1 @@
1460c99dfa21333b31a4af92cc4c18110ef62d56

View file

@ -0,0 +1 @@
28da4aa5ebde6007021646d01b238b1b362bbd7c

View file

@ -0,0 +1,27 @@
C:\Users\l.farina\Desktop\UCRM_stage\RSTP_DSLink\RSTP_DSLink\obj\Debug\netcoreapp3.1\RSTP_DSLink.csproj.AssemblyReference.cache
C:\Users\l.farina\Desktop\UCRM_stage\RSTP_DSLink\RSTP_DSLink\obj\Debug\netcoreapp3.1\RSTP_DSLink.AssemblyInfoInputs.cache
C:\Users\l.farina\Desktop\UCRM_stage\RSTP_DSLink\RSTP_DSLink\obj\Debug\netcoreapp3.1\RSTP_DSLink.AssemblyInfo.cs
C:\Users\l.farina\Desktop\UCRM_stage\RSTP_DSLink\RSTP_DSLink\obj\Debug\netcoreapp3.1\RSTP_DSLink.csproj.CoreCompileInputs.cache
C:\Users\l.farina\Desktop\UCRM_stage\RSTP_DSLink\RSTP_DSLink\bin\Debug\netcoreapp3.1\RSTP_DSLink.exe
C:\Users\l.farina\Desktop\UCRM_stage\RSTP_DSLink\RSTP_DSLink\bin\Debug\netcoreapp3.1\RSTP_DSLink.deps.json
C:\Users\l.farina\Desktop\UCRM_stage\RSTP_DSLink\RSTP_DSLink\bin\Debug\netcoreapp3.1\RSTP_DSLink.runtimeconfig.json
C:\Users\l.farina\Desktop\UCRM_stage\RSTP_DSLink\RSTP_DSLink\bin\Debug\netcoreapp3.1\RSTP_DSLink.runtimeconfig.dev.json
C:\Users\l.farina\Desktop\UCRM_stage\RSTP_DSLink\RSTP_DSLink\bin\Debug\netcoreapp3.1\RSTP_DSLink.dll
C:\Users\l.farina\Desktop\UCRM_stage\RSTP_DSLink\RSTP_DSLink\bin\Debug\netcoreapp3.1\RSTP_DSLink.pdb
C:\Users\l.farina\Desktop\UCRM_stage\RSTP_DSLink\RSTP_DSLink\bin\Debug\netcoreapp3.1\CommandLine.dll
C:\Users\l.farina\Desktop\UCRM_stage\RSTP_DSLink\RSTP_DSLink\bin\Debug\netcoreapp3.1\MsgPack.dll
C:\Users\l.farina\Desktop\UCRM_stage\RSTP_DSLink\RSTP_DSLink\bin\Debug\netcoreapp3.1\Newtonsoft.Json.dll
C:\Users\l.farina\Desktop\UCRM_stage\RSTP_DSLink\RSTP_DSLink\bin\Debug\netcoreapp3.1\BouncyCastle.Crypto.dll
C:\Users\l.farina\Desktop\UCRM_stage\RSTP_DSLink\RSTP_DSLink\bin\Debug\netcoreapp3.1\Serilog.dll
C:\Users\l.farina\Desktop\UCRM_stage\RSTP_DSLink\RSTP_DSLink\bin\Debug\netcoreapp3.1\Serilog.Sinks.Console.dll
C:\Users\l.farina\Desktop\UCRM_stage\RSTP_DSLink\RSTP_DSLink\bin\Debug\netcoreapp3.1\Serilog.Sinks.Debug.dll
C:\Users\l.farina\Desktop\UCRM_stage\RSTP_DSLink\RSTP_DSLink\bin\Debug\netcoreapp3.1\Serilog.Sinks.File.dll
C:\Users\l.farina\Desktop\UCRM_stage\RSTP_DSLink\RSTP_DSLink\bin\Debug\netcoreapp3.1\Serilog.Sinks.RollingFile.dll
C:\Users\l.farina\Desktop\UCRM_stage\RSTP_DSLink\RSTP_DSLink\bin\Debug\netcoreapp3.1\StandardStorage.dll
C:\Users\l.farina\Desktop\UCRM_stage\RSTP_DSLink\RSTP_DSLink\bin\Debug\netcoreapp3.1\System.CodeDom.dll
C:\Users\l.farina\Desktop\UCRM_stage\RSTP_DSLink\RSTP_DSLink\bin\Debug\netcoreapp3.1\System.Security.Permissions.dll
C:\Users\l.farina\Desktop\UCRM_stage\RSTP_DSLink\RSTP_DSLink\bin\Debug\netcoreapp3.1\DSLink.dll
C:\Users\l.farina\Desktop\UCRM_stage\RSTP_DSLink\RSTP_DSLink\obj\Debug\netcoreapp3.1\RSTP_DSLink.csproj.CopyComplete
C:\Users\l.farina\Desktop\UCRM_stage\RSTP_DSLink\RSTP_DSLink\obj\Debug\netcoreapp3.1\RSTP_DSLink.dll
C:\Users\l.farina\Desktop\UCRM_stage\RSTP_DSLink\RSTP_DSLink\obj\Debug\netcoreapp3.1\RSTP_DSLink.pdb
C:\Users\l.farina\Desktop\UCRM_stage\RSTP_DSLink\RSTP_DSLink\obj\Debug\netcoreapp3.1\RSTP_DSLink.genruntimeconfig.cache

View file

@ -0,0 +1 @@
ad1a4f88991fe69ed4da21939be6efa654633ebb

View file

@ -0,0 +1,118 @@
{
"format": 1,
"restore": {
"C:\\Users\\l.farina\\Desktop\\UCRM_stage\\RSTP_DSLink\\RSTP_DSLink\\RSTP_DSLink.csproj": {}
},
"projects": {
"C:\\Users\\l.farina\\Desktop\\UCRM_stage\\RSTP_DSLink\\RSTP_DSLink\\RSTP_DSLink.csproj": {
"version": "1.0.0",
"restore": {
"projectUniqueName": "C:\\Users\\l.farina\\Desktop\\UCRM_stage\\RSTP_DSLink\\RSTP_DSLink\\RSTP_DSLink.csproj",
"projectName": "RSTP_DSLink",
"projectPath": "C:\\Users\\l.farina\\Desktop\\UCRM_stage\\RSTP_DSLink\\RSTP_DSLink\\RSTP_DSLink.csproj",
"packagesPath": "C:\\Users\\l.farina\\.nuget\\packages\\",
"outputPath": "C:\\Users\\l.farina\\Desktop\\UCRM_stage\\RSTP_DSLink\\RSTP_DSLink\\obj\\",
"projectStyle": "PackageReference",
"configFilePaths": [
"C:\\Users\\l.farina\\AppData\\Roaming\\NuGet\\NuGet.Config",
"C:\\Program Files (x86)\\NuGet\\Config\\Microsoft.VisualStudio.Offline.config"
],
"originalTargetFrameworks": [
"netcoreapp3.1"
],
"sources": {
"C:\\Program Files (x86)\\Microsoft SDKs\\NuGetPackages\\": {},
"https://api.nuget.org/v3/index.json": {}
},
"frameworks": {
"netcoreapp3.1": {
"targetAlias": "netcoreapp3.1",
"projectReferences": {}
}
},
"warningProperties": {
"warnAsError": [
"NU1605"
]
}
},
"frameworks": {
"netcoreapp3.1": {
"targetAlias": "netcoreapp3.1",
"dependencies": {
"CommandLineParser": {
"target": "Package",
"version": "[2.8.0, )"
},
"LibLog": {
"include": "Runtime, Build, Native, ContentFiles, Analyzers, BuildTransitive",
"suppressParent": "All",
"target": "Package",
"version": "[5.0.8, )"
},
"Microsoft.CSharp": {
"target": "Package",
"version": "[4.7.0, )"
},
"MsgPack.Cli": {
"target": "Package",
"version": "[1.0.1, )"
},
"NETStandard.Library": {
"target": "Package",
"version": "[2.0.3, )"
},
"Newtonsoft.Json": {
"target": "Package",
"version": "[13.0.1, )"
},
"Portable.BouncyCastle": {
"target": "Package",
"version": "[1.8.10, )"
},
"Serilog": {
"target": "Package",
"version": "[2.10.0, )"
},
"Serilog.Sinks.Console": {
"target": "Package",
"version": "[4.0.0, )"
},
"Serilog.Sinks.Debug": {
"target": "Package",
"version": "[2.0.0, )"
},
"Serilog.Sinks.File": {
"target": "Package",
"version": "[5.0.0, )"
},
"Serilog.Sinks.RollingFile": {
"target": "Package",
"version": "[3.3.0, )"
},
"StandardStorage": {
"target": "Package",
"version": "[0.1.1, )"
}
},
"imports": [
"net461",
"net462",
"net47",
"net471",
"net472",
"net48"
],
"assetTargetFallback": true,
"warn": true,
"frameworkReferences": {
"Microsoft.NETCore.App": {
"privateAssets": "all"
}
},
"runtimeIdentifierGraphPath": "C:\\Program Files\\dotnet\\sdk\\5.0.301\\RuntimeIdentifierGraph.json"
}
}
}
}
}

View file

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects>
</PropertyGroup>
<ImportGroup Condition=" '$(ExcludeRestorePackageImports)' != 'true' ">
<Import Project="$(NuGetPackageRoot)netstandard.library\2.0.3\build\netstandard2.0\NETStandard.Library.targets" Condition="Exists('$(NuGetPackageRoot)netstandard.library\2.0.3\build\netstandard2.0\NETStandard.Library.targets')" />
</ImportGroup>
</Project>

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,45 @@
{
"version": 2,
"dgSpecHash": "p93DWVlIreOhMiKICOvM553HiyS7BkFL8VBKcoai0hLZPGo2yxkwr0EARlt7be9Vd7d6a6mXbbQi+O7kkowbtg==",
"success": true,
"projectFilePath": "C:\\Users\\l.farina\\Desktop\\UCRM_stage\\RSTP_DSLink\\RSTP_DSLink\\RSTP_DSLink.csproj",
"expectedPackageFiles": [
"C:\\Users\\l.farina\\.nuget\\packages\\commandlineparser\\2.8.0\\commandlineparser.2.8.0.nupkg.sha512",
"C:\\Users\\l.farina\\.nuget\\packages\\liblog\\5.0.8\\liblog.5.0.8.nupkg.sha512",
"C:\\Users\\l.farina\\.nuget\\packages\\microsoft.csharp\\4.7.0\\microsoft.csharp.4.7.0.nupkg.sha512",
"C:\\Users\\l.farina\\.nuget\\packages\\microsoft.netcore.platforms\\2.0.0\\microsoft.netcore.platforms.2.0.0.nupkg.sha512",
"C:\\Users\\l.farina\\.nuget\\packages\\microsoft.netcore.targets\\1.1.0\\microsoft.netcore.targets.1.1.0.nupkg.sha512",
"C:\\Users\\l.farina\\.nuget\\packages\\msgpack.cli\\1.0.1\\msgpack.cli.1.0.1.nupkg.sha512",
"C:\\Users\\l.farina\\.nuget\\packages\\netstandard.library\\2.0.3\\netstandard.library.2.0.3.nupkg.sha512",
"C:\\Users\\l.farina\\.nuget\\packages\\newtonsoft.json\\13.0.1\\newtonsoft.json.13.0.1.nupkg.sha512",
"C:\\Users\\l.farina\\.nuget\\packages\\portable.bouncycastle\\1.8.10\\portable.bouncycastle.1.8.10.nupkg.sha512",
"C:\\Users\\l.farina\\.nuget\\packages\\serilog\\2.10.0\\serilog.2.10.0.nupkg.sha512",
"C:\\Users\\l.farina\\.nuget\\packages\\serilog.sinks.console\\4.0.0\\serilog.sinks.console.4.0.0.nupkg.sha512",
"C:\\Users\\l.farina\\.nuget\\packages\\serilog.sinks.debug\\2.0.0\\serilog.sinks.debug.2.0.0.nupkg.sha512",
"C:\\Users\\l.farina\\.nuget\\packages\\serilog.sinks.file\\5.0.0\\serilog.sinks.file.5.0.0.nupkg.sha512",
"C:\\Users\\l.farina\\.nuget\\packages\\serilog.sinks.rollingfile\\3.3.0\\serilog.sinks.rollingfile.3.3.0.nupkg.sha512",
"C:\\Users\\l.farina\\.nuget\\packages\\standardstorage\\0.1.1\\standardstorage.0.1.1.nupkg.sha512",
"C:\\Users\\l.farina\\.nuget\\packages\\system.codedom\\4.4.0\\system.codedom.4.4.0.nupkg.sha512",
"C:\\Users\\l.farina\\.nuget\\packages\\system.globalization\\4.3.0\\system.globalization.4.3.0.nupkg.sha512",
"C:\\Users\\l.farina\\.nuget\\packages\\system.io\\4.3.0\\system.io.4.3.0.nupkg.sha512",
"C:\\Users\\l.farina\\.nuget\\packages\\system.io.filesystem.primitives\\4.0.1\\system.io.filesystem.primitives.4.0.1.nupkg.sha512",
"C:\\Users\\l.farina\\.nuget\\packages\\system.numerics.vectors\\4.3.0\\system.numerics.vectors.4.3.0.nupkg.sha512",
"C:\\Users\\l.farina\\.nuget\\packages\\system.reflection\\4.3.0\\system.reflection.4.3.0.nupkg.sha512",
"C:\\Users\\l.farina\\.nuget\\packages\\system.reflection.emit\\4.3.0\\system.reflection.emit.4.3.0.nupkg.sha512",
"C:\\Users\\l.farina\\.nuget\\packages\\system.reflection.emit.ilgeneration\\4.3.0\\system.reflection.emit.ilgeneration.4.3.0.nupkg.sha512",
"C:\\Users\\l.farina\\.nuget\\packages\\system.reflection.emit.lightweight\\4.3.0\\system.reflection.emit.lightweight.4.3.0.nupkg.sha512",
"C:\\Users\\l.farina\\.nuget\\packages\\system.reflection.primitives\\4.3.0\\system.reflection.primitives.4.3.0.nupkg.sha512",
"C:\\Users\\l.farina\\.nuget\\packages\\system.resources.resourcemanager\\4.3.0\\system.resources.resourcemanager.4.3.0.nupkg.sha512",
"C:\\Users\\l.farina\\.nuget\\packages\\system.runtime\\4.3.0\\system.runtime.4.3.0.nupkg.sha512",
"C:\\Users\\l.farina\\.nuget\\packages\\system.runtime.extensions\\4.3.0\\system.runtime.extensions.4.3.0.nupkg.sha512",
"C:\\Users\\l.farina\\.nuget\\packages\\system.runtime.handles\\4.0.1\\system.runtime.handles.4.0.1.nupkg.sha512",
"C:\\Users\\l.farina\\.nuget\\packages\\system.runtime.interopservices\\4.1.0\\system.runtime.interopservices.4.1.0.nupkg.sha512",
"C:\\Users\\l.farina\\.nuget\\packages\\system.security.accesscontrol\\4.4.0\\system.security.accesscontrol.4.4.0.nupkg.sha512",
"C:\\Users\\l.farina\\.nuget\\packages\\system.security.permissions\\4.4.1\\system.security.permissions.4.4.1.nupkg.sha512",
"C:\\Users\\l.farina\\.nuget\\packages\\system.security.principal.windows\\4.4.0\\system.security.principal.windows.4.4.0.nupkg.sha512",
"C:\\Users\\l.farina\\.nuget\\packages\\system.text.encoding\\4.3.0\\system.text.encoding.4.3.0.nupkg.sha512",
"C:\\Users\\l.farina\\.nuget\\packages\\system.text.encoding.extensions\\4.0.11\\system.text.encoding.extensions.4.0.11.nupkg.sha512",
"C:\\Users\\l.farina\\.nuget\\packages\\system.threading.tasks\\4.3.0\\system.threading.tasks.4.3.0.nupkg.sha512"
],
"logs": []
}