From 30d1ab36b6bdd4538651e06f2ad0ceda823d4239 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B3=BD=E5=A8=81=20=E7=8E=8B?= <1585955375@qq.com> Date: Sat, 16 Apr 2022 00:57:06 +0800 Subject: [PATCH 1/6] =?UTF-8?q?skyapm=20dotnet=20=E5=AF=B9=E6=8E=A5?= =?UTF-8?q?=E6=97=A5=E5=BF=97=E8=AE=B0=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Controllers/WeatherForecastController.cs | 38 ++++++ sample/Sky.Apm.Sample.Logging/Program.cs | 31 +++++ .../Properties/launchSettings.json | 32 +++++ .../Sky.Apm.Sample.Logging.csproj | 24 ++++ sample/Sky.Apm.Sample.Logging/Test.cs | 17 +++ .../Sky.Apm.Sample.Logging/WeatherForecast.cs | 13 ++ .../appsettings.Development.json | 8 ++ .../Sky.Apm.Sample.Logging/appsettings.json | 9 ++ sample/Sky.Apm.Sample.Logging/skyapm.json | 30 ++++ skyapm-dotnet.sln | 11 +- .../Tracing/Segments/LoggerContext.cs | 11 ++ .../Transport/ILoggerContextContextMapper.cs | 8 ++ .../Transport/ILoggerReporter.cs | 14 ++ .../Transport/ISkyApmLogDispatcher.cs | 16 +++ .../Transport/LoggerRequest.cs | 13 ++ .../SkyApmHostingStartup.cs | 6 +- .../Extensions/ServiceCollectionExtensions.cs | 11 +- src/SkyApm.Core/Service/LogReportService.cs | 38 ++++++ src/SkyApm.Core/SkyApm.Core.csproj | 8 ++ src/SkyApm.Core/SkyLogging/SkyApmLogger.cs | 129 ++++++++++++++++++ .../SkyLogging/SkyApmLoggerExtensions.cs | 36 +++++ .../SkyLogging/SkyApmLoggerOptionsSetup.cs | 51 +++++++ .../SkyLogging/SkyApmLoggerProvider.cs | 101 ++++++++++++++ .../Tracing/SegmentContextFactory.cs | 1 - .../AsyncQueueSkyApmLogDispatcher.cs | 87 ++++++++++++ .../Transport/LoggerContextContextMapper.cs | 24 ++++ .../Common/SegmentV8Helpers.cs | 6 +- .../V8/LoggerReporter.cs | 91 ++++++++++++ .../V8/SegmentReporter.cs | 37 +++++ 29 files changed, 895 insertions(+), 6 deletions(-) create mode 100644 sample/Sky.Apm.Sample.Logging/Controllers/WeatherForecastController.cs create mode 100644 sample/Sky.Apm.Sample.Logging/Program.cs create mode 100644 sample/Sky.Apm.Sample.Logging/Properties/launchSettings.json create mode 100644 sample/Sky.Apm.Sample.Logging/Sky.Apm.Sample.Logging.csproj create mode 100644 sample/Sky.Apm.Sample.Logging/Test.cs create mode 100644 sample/Sky.Apm.Sample.Logging/WeatherForecast.cs create mode 100644 sample/Sky.Apm.Sample.Logging/appsettings.Development.json create mode 100644 sample/Sky.Apm.Sample.Logging/appsettings.json create mode 100644 sample/Sky.Apm.Sample.Logging/skyapm.json create mode 100644 src/SkyApm.Abstractions/Tracing/Segments/LoggerContext.cs create mode 100644 src/SkyApm.Abstractions/Transport/ILoggerContextContextMapper.cs create mode 100644 src/SkyApm.Abstractions/Transport/ILoggerReporter.cs create mode 100644 src/SkyApm.Abstractions/Transport/ISkyApmLogDispatcher.cs create mode 100644 src/SkyApm.Abstractions/Transport/LoggerRequest.cs create mode 100644 src/SkyApm.Core/Service/LogReportService.cs create mode 100644 src/SkyApm.Core/SkyLogging/SkyApmLogger.cs create mode 100644 src/SkyApm.Core/SkyLogging/SkyApmLoggerExtensions.cs create mode 100644 src/SkyApm.Core/SkyLogging/SkyApmLoggerOptionsSetup.cs create mode 100644 src/SkyApm.Core/SkyLogging/SkyApmLoggerProvider.cs create mode 100644 src/SkyApm.Core/Transport/AsyncQueueSkyApmLogDispatcher.cs create mode 100644 src/SkyApm.Core/Transport/LoggerContextContextMapper.cs create mode 100644 src/SkyApm.Transport.Grpc/V8/LoggerReporter.cs diff --git a/sample/Sky.Apm.Sample.Logging/Controllers/WeatherForecastController.cs b/sample/Sky.Apm.Sample.Logging/Controllers/WeatherForecastController.cs new file mode 100644 index 00000000..4ab5889a --- /dev/null +++ b/sample/Sky.Apm.Sample.Logging/Controllers/WeatherForecastController.cs @@ -0,0 +1,38 @@ +using Microsoft.AspNetCore.Mvc; +using SkyApm.Tracing; + +namespace Sky.Apm.Sample.Logging.Controllers +{ + [ApiController] + [Route("apitest")] + public class WeatherForecastController : ControllerBase + { + private static readonly string[] Summaries = new[] + { + "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" + }; + + private readonly Test _test; + private readonly ILogger _logger; + public WeatherForecastController(ILogger logger, Test test) + { + _logger = logger; + _test = test; + } + + [HttpGet(Name = "GetWeatherForecast")] + public IEnumerable Get() + { + //Console.WriteLine(_entrySegmentContextAccessor.Context?.TraceId); + _logger.LogInformation("我用来测试自定义日志!!!!!!!!!!!!"); + _test.Create(); + return Enumerable.Range(1, 5).Select(index => new WeatherForecast + { + Date = DateTime.Now.AddDays(index), + TemperatureC = Random.Shared.Next(-20, 55), + Summary = Summaries[Random.Shared.Next(Summaries.Length)] + }) + .ToArray(); + } + } +} \ No newline at end of file diff --git a/sample/Sky.Apm.Sample.Logging/Program.cs b/sample/Sky.Apm.Sample.Logging/Program.cs new file mode 100644 index 00000000..d0ae32d6 --- /dev/null +++ b/sample/Sky.Apm.Sample.Logging/Program.cs @@ -0,0 +1,31 @@ +//using Sky.Apm.Sample.Logging.Test; + +using Sky.Apm.Sample.Logging; + +var builder = WebApplication.CreateBuilder(args); + +// Add services to the container. + +builder.Services.AddControllers(); +// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(); +builder.Services.AddScoped(); +//builder.Services.AddLogging(logging => +//{ +// logging.AddSkyApmLogger(); +//}); +var app = builder.Build(); + +// Configure the HTTP request pipeline. +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); +} + +app.UseAuthorization(); + +app.MapControllers(); + +app.Run(); diff --git a/sample/Sky.Apm.Sample.Logging/Properties/launchSettings.json b/sample/Sky.Apm.Sample.Logging/Properties/launchSettings.json new file mode 100644 index 00000000..48a53e29 --- /dev/null +++ b/sample/Sky.Apm.Sample.Logging/Properties/launchSettings.json @@ -0,0 +1,32 @@ +锘縶 + "$schema": "https://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:2952", + "sslPort": 0 + } + }, + "profiles": { + "Sky.Apm.Sample.Logging": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "http://localhost:5008", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "SkyAPM.Agent.AspNetCore" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/sample/Sky.Apm.Sample.Logging/Sky.Apm.Sample.Logging.csproj b/sample/Sky.Apm.Sample.Logging/Sky.Apm.Sample.Logging.csproj new file mode 100644 index 00000000..819f0ffd --- /dev/null +++ b/sample/Sky.Apm.Sample.Logging/Sky.Apm.Sample.Logging.csproj @@ -0,0 +1,24 @@ + + + + net6.0 + enable + enable + + + + + + + + + + + + + + + + + + diff --git a/sample/Sky.Apm.Sample.Logging/Test.cs b/sample/Sky.Apm.Sample.Logging/Test.cs new file mode 100644 index 00000000..d2fe7c57 --- /dev/null +++ b/sample/Sky.Apm.Sample.Logging/Test.cs @@ -0,0 +1,17 @@ +锘縩amespace Sky.Apm.Sample.Logging +{ + public class Test + { + private readonly ILogger _logger; + + public Test(ILogger logger) + { + _logger = logger; + } + + public void Create() + { + _logger.LogError("鍒涘缓浜嗕竴涓敤鎴峰璞",new List { "asdasdas","3ewqeqdad","q34asdase2qq"}); + } + } +} diff --git a/sample/Sky.Apm.Sample.Logging/WeatherForecast.cs b/sample/Sky.Apm.Sample.Logging/WeatherForecast.cs new file mode 100644 index 00000000..d3164cf5 --- /dev/null +++ b/sample/Sky.Apm.Sample.Logging/WeatherForecast.cs @@ -0,0 +1,13 @@ +namespace Sky.Apm.Sample.Logging +{ + public class WeatherForecast + { + public DateTime Date { get; set; } + + public int TemperatureC { get; set; } + + public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); + + public string? Summary { get; set; } + } +} \ No newline at end of file diff --git a/sample/Sky.Apm.Sample.Logging/appsettings.Development.json b/sample/Sky.Apm.Sample.Logging/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/sample/Sky.Apm.Sample.Logging/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/sample/Sky.Apm.Sample.Logging/appsettings.json b/sample/Sky.Apm.Sample.Logging/appsettings.json new file mode 100644 index 00000000..10f68b8c --- /dev/null +++ b/sample/Sky.Apm.Sample.Logging/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/sample/Sky.Apm.Sample.Logging/skyapm.json b/sample/Sky.Apm.Sample.Logging/skyapm.json new file mode 100644 index 00000000..bb2eea93 --- /dev/null +++ b/sample/Sky.Apm.Sample.Logging/skyapm.json @@ -0,0 +1,30 @@ +{ + "SkyWalking": { + "ServiceName": "Sky.Apm.Sample.Logging", + "Namespace": "", + "HeaderVersions": [ + "sw8" + ], + "Sampling": { + "SamplePer3Secs": -1, + "Percentage": -1.0 + }, + "Logging": { + "Level": "Information", + "FilePath": "logs\\skyapm-{Date}.log" + }, + "Transport": { + "Interval": 3000, + "ProtocolVersion": "v8", + "QueueSize": 30000, + "BatchSize": 3000, + "gRPC": { + "Servers": "101.34.26.221:40009", + "Timeout": 10000, + "ConnectTimeout": 10000, + "ReportTimeout": 600000 //, + //"Authentication": "" + } + } + } +} \ No newline at end of file diff --git a/skyapm-dotnet.sln b/skyapm-dotnet.sln index f0cac3b8..b73c4e9e 100644 --- a/skyapm-dotnet.sln +++ b/skyapm-dotnet.sln @@ -1,7 +1,7 @@ 锘 Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.28729.10 +# Visual Studio Version 17 +VisualStudioVersion = 17.1.32407.343 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{05BF0D4E-C824-4EC8-8330-36C1FC49910E}" EndProject @@ -109,6 +109,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SkyApm.Diagnostics.FreeSql" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SkyApm.Sample.FreeSqlSqlite", "sample\SkyApm.Sample.FreeSql\SkyApm.Sample.FreeSqlSqlite.csproj", "{B1EF3295-4BF0-489F-8063-C9E3DAE20AA9}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sky.Apm.Sample.Logging", "sample\Sky.Apm.Sample.Logging\Sky.Apm.Sample.Logging.csproj", "{D35905EC-EB46-4A3D-BD2B-02C4C868BC65}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -243,6 +245,10 @@ Global {B1EF3295-4BF0-489F-8063-C9E3DAE20AA9}.Debug|Any CPU.Build.0 = Debug|Any CPU {B1EF3295-4BF0-489F-8063-C9E3DAE20AA9}.Release|Any CPU.ActiveCfg = Release|Any CPU {B1EF3295-4BF0-489F-8063-C9E3DAE20AA9}.Release|Any CPU.Build.0 = Release|Any CPU + {D35905EC-EB46-4A3D-BD2B-02C4C868BC65}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D35905EC-EB46-4A3D-BD2B-02C4C868BC65}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D35905EC-EB46-4A3D-BD2B-02C4C868BC65}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D35905EC-EB46-4A3D-BD2B-02C4C868BC65}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -289,6 +295,7 @@ Global {8D3C5573-C282-45F5-A7F4-2E323F322CB7} = {B5E677CF-2920-4B0A-A056-E73F6B2CF2BC} {82580A47-9DBC-43E8-B581-0C35147B4FAD} = {B5E677CF-2920-4B0A-A056-E73F6B2CF2BC} {B1EF3295-4BF0-489F-8063-C9E3DAE20AA9} = {844CEACD-4C85-4B15-9E2B-892B01FDA4BB} + {D35905EC-EB46-4A3D-BD2B-02C4C868BC65} = {844CEACD-4C85-4B15-9E2B-892B01FDA4BB} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {94C0DA2C-CCCB-4314-93A2-9809B5DD0583} diff --git a/src/SkyApm.Abstractions/Tracing/Segments/LoggerContext.cs b/src/SkyApm.Abstractions/Tracing/Segments/LoggerContext.cs new file mode 100644 index 00000000..972f6500 --- /dev/null +++ b/src/SkyApm.Abstractions/Tracing/Segments/LoggerContext.cs @@ -0,0 +1,11 @@ +锘縰sing System.Collections.Generic; + +namespace SkyApm.Tracing.Segments +{ + public class LoggerContext + { + public Dictionary Logs { get; set; } + + public SegmentContext SegmentContext { get; set; } + } +} diff --git a/src/SkyApm.Abstractions/Transport/ILoggerContextContextMapper.cs b/src/SkyApm.Abstractions/Transport/ILoggerContextContextMapper.cs new file mode 100644 index 00000000..a5894d93 --- /dev/null +++ b/src/SkyApm.Abstractions/Transport/ILoggerContextContextMapper.cs @@ -0,0 +1,8 @@ +锘縰sing SkyApm.Tracing.Segments; +namespace SkyApm.Transport +{ + public interface ILoggerContextContextMapper + { + LoggerRequest Map(LoggerContext loggerContext); + } +} diff --git a/src/SkyApm.Abstractions/Transport/ILoggerReporter.cs b/src/SkyApm.Abstractions/Transport/ILoggerReporter.cs new file mode 100644 index 00000000..cab7265b --- /dev/null +++ b/src/SkyApm.Abstractions/Transport/ILoggerReporter.cs @@ -0,0 +1,14 @@ +锘縰sing System; +using System.Collections.Generic; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace SkyApm.Transport +{ + public interface ILoggerReporter + { + Task ReportAsync(IReadOnlyCollection loggerRequests, + CancellationToken cancellationToken = default(CancellationToken)); + } +} diff --git a/src/SkyApm.Abstractions/Transport/ISkyApmLogDispatcher.cs b/src/SkyApm.Abstractions/Transport/ISkyApmLogDispatcher.cs new file mode 100644 index 00000000..f9e9d982 --- /dev/null +++ b/src/SkyApm.Abstractions/Transport/ISkyApmLogDispatcher.cs @@ -0,0 +1,16 @@ +锘縰sing SkyApm.Tracing.Segments; +using System.Threading; +using System.Threading.Tasks; + +namespace SkyApm.Transport +{ + public interface ISkyApmLogDispatcher + { + bool Dispatch(LoggerContext loggerContext); + + Task Flush(CancellationToken token = default(CancellationToken)); + + void Close(); + + } +} diff --git a/src/SkyApm.Abstractions/Transport/LoggerRequest.cs b/src/SkyApm.Abstractions/Transport/LoggerRequest.cs new file mode 100644 index 00000000..e2eb14c1 --- /dev/null +++ b/src/SkyApm.Abstractions/Transport/LoggerRequest.cs @@ -0,0 +1,13 @@ +锘縰sing System; +using System.Collections.Generic; +using System.Text; + +namespace SkyApm.Transport +{ + public class LoggerRequest + { + public Dictionary Logs { get; set; } + + public SegmentRequest SegmentRequest { get; set; } + } +} diff --git a/src/SkyApm.Agent.AspNetCore/SkyApmHostingStartup.cs b/src/SkyApm.Agent.AspNetCore/SkyApmHostingStartup.cs index 5adc7b2e..39ad0b32 100644 --- a/src/SkyApm.Agent.AspNetCore/SkyApmHostingStartup.cs +++ b/src/SkyApm.Agent.AspNetCore/SkyApmHostingStartup.cs @@ -29,7 +29,11 @@ internal class SkyApmHostingStartup : IHostingStartup { public void Configure(IWebHostBuilder builder) { - builder.ConfigureServices(services => services.AddSkyAPM(ext => ext.AddAspNetCoreHosting())); + builder.ConfigureServices(services => services.AddSkyAPM(ext => ext.AddAspNetCoreHosting()) + .AddLogging(logging => + { + logging.AddSkyApmLogger(); + })); } } } \ No newline at end of file diff --git a/src/SkyApm.Agent.Hosting/Extensions/ServiceCollectionExtensions.cs b/src/SkyApm.Agent.Hosting/Extensions/ServiceCollectionExtensions.cs index 8eb06b33..5bf47fc3 100644 --- a/src/SkyApm.Agent.Hosting/Extensions/ServiceCollectionExtensions.cs +++ b/src/SkyApm.Agent.Hosting/Extensions/ServiceCollectionExtensions.cs @@ -56,6 +56,7 @@ internal static IServiceCollection AddSkyAPMCore(this IServiceCollection service services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); @@ -66,7 +67,7 @@ internal static IServiceCollection AddSkyAPMCore(this IServiceCollection service services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); - services.AddTracing().AddSampling().AddGrpcTransport().AddSkyApmLogging(); + services.AddTracing().AddSkyApmLogger().AddSampling().AddGrpcTransport().AddSkyApmLogging(); var extensions = services.AddSkyApmExtensions() .AddHttpClient() .AddGrpcClient() @@ -95,6 +96,13 @@ private static IServiceCollection AddTracing(this IServiceCollection services) return services; } + public static IServiceCollection AddSkyApmLogger(this IServiceCollection services) + { + services.AddSingleton(); + services.AddSingleton(); + return services; + } + private static IServiceCollection AddSampling(this IServiceCollection services) { services.AddSingleton(); @@ -108,6 +116,7 @@ private static IServiceCollection AddSampling(this IServiceCollection services) private static IServiceCollection AddGrpcTransport(this IServiceCollection services) { services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); diff --git a/src/SkyApm.Core/Service/LogReportService.cs b/src/SkyApm.Core/Service/LogReportService.cs new file mode 100644 index 00000000..cf9110a6 --- /dev/null +++ b/src/SkyApm.Core/Service/LogReportService.cs @@ -0,0 +1,38 @@ +锘縰sing SkyApm.Config; +using SkyApm.Logging; +using SkyApm.Transport; +using System; +using System.Threading; +using System.Threading.Tasks; + +namespace SkyApm.Service +{ + public class LogReportService : ExecutionService + { + + private readonly ISkyApmLogDispatcher _dispatcher; + private readonly TransportConfig _config; + public LogReportService(IConfigAccessor configAccessor, ISkyApmLogDispatcher dispatcher, + IRuntimeEnvironment runtimeEnvironment, ILoggerFactory loggerFactory) + : base(runtimeEnvironment, loggerFactory) + { + _dispatcher = dispatcher; + _config = configAccessor.Get(); + Period = TimeSpan.FromMilliseconds(_config.Interval); + } + + protected override TimeSpan DueTime { get; } = TimeSpan.FromSeconds(3); + + protected override TimeSpan Period { get; } + + protected override Task ExecuteAsync(CancellationToken cancellationToken) + { + return _dispatcher.Flush(cancellationToken); + } + protected override Task Stopping(CancellationToken cancellationToke) + { + _dispatcher.Close(); + return Task.CompletedTask; + } + } +} diff --git a/src/SkyApm.Core/SkyApm.Core.csproj b/src/SkyApm.Core/SkyApm.Core.csproj index ed627d3d..2d57777a 100644 --- a/src/SkyApm.Core/SkyApm.Core.csproj +++ b/src/SkyApm.Core/SkyApm.Core.csproj @@ -12,8 +12,16 @@ netstandard2.0 $(DefineConstants);SPAN + + + + diff --git a/src/SkyApm.Core/SkyLogging/SkyApmLogger.cs b/src/SkyApm.Core/SkyLogging/SkyApmLogger.cs new file mode 100644 index 00000000..980e917b --- /dev/null +++ b/src/SkyApm.Core/SkyLogging/SkyApmLogger.cs @@ -0,0 +1,129 @@ +锘縰sing Microsoft.Extensions.Logging; +using SkyApm.Tracing; +using SkyApm.Tracing.Segments; +using SkyApm.Transport; +using System; +using System.Collections.Generic; + +namespace SkyApm.Core.Logging +{ + public class SkyApmLogger : ILogger + { + + public SkyApmLoggerProvider Provider { get; private set; } + public string Category { get; private set; } + private readonly IEntrySegmentContextAccessor _entrySegmentContextAccessor; + + private readonly ISkyApmLogDispatcher _skyApmLogDispatcher; + public SkyApmLogger(SkyApmLoggerProvider Provider, IEntrySegmentContextAccessor entrySegmentContextAccessor, ISkyApmLogDispatcher skyApmLogDispatcher, string Category) + { + this.Provider = Provider; + _entrySegmentContextAccessor = entrySegmentContextAccessor; + this.Category = Category; + _skyApmLogDispatcher = skyApmLogDispatcher; + } + + IDisposable ILogger.BeginScope(TState state) + { + return Provider.ScopeProvider.Push(state); + } + + bool ILogger.IsEnabled(LogLevel logLevel) + { + return logLevel != LogLevel.None; + } + + void ILogger.Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter) + { + if ((this as ILogger).IsEnabled(logLevel)) + { + var logs = new Dictionary(); + logs.Add("className", this.Category); + logs.Add("Level", logLevel); + logs.Add("logMessage", exception?.Message ?? state.ToString()); + logs.Add("eventId", eventId.ToString()); + logs.Add("state", state.ToString()); + if (state is string) + { + logs.Add("stateText", state.ToString()); + } + else if (state is IEnumerable> Properties) + { + var stateProperties = new Dictionary(); + foreach (KeyValuePair item in Properties) + { + stateProperties.Add(item.Key, item.Value); + } + logs.Add("stateProperties", stateProperties); + } + var logContext = new LoggerContext() + { + Logs = logs, + SegmentContext = _entrySegmentContextAccessor.Context, + }; + _skyApmLogDispatcher.Dispatch(logContext); + #region MyRegion + + + //SkyApmLogEntry Info = new SkyApmLogEntry(); + //Info.Category = this.Category; + //Info.Level = logLevel.ToString(); + //Info.Text = exception?.Message ?? state.ToString(); // formatter(state, exception) + //Info.Exception = exception; + //Info.EventId = eventId; + //Info.State = state; + + //// well, you never know what it really is + //if (state is string) + //{ + // Info.StateText = state.ToString(); + //} + //// in case we have to do with a message template, lets get the keys and values (for Structured Logging providers) + //// SEE: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging#log-message-template + //// SEE: https://softwareengineering.stackexchange.com/questions/312197/benefits-of-structured-logging-vs-basic-logging + //else if (state is IEnumerable> Properties) + //{ + // Info.StateProperties = new Dictionary(); + + // foreach (KeyValuePair item in Properties) + // { + // Info.StateProperties[item.Key] = item.Value; + // } + //} + + // gather info about scope(s), if any + //if (Provider.ScopeProvider != null) + //{ + // Provider.ScopeProvider.ForEachScope((value, loggingProps) => + // { + // if (Info.Scopes == null) + // Info.Scopes = new List(); + + // LogScopeInfo Scope = new LogScopeInfo(); + // Info.Scopes.Add(Scope); + + // if (value is string) + // { + // Scope.Text = value.ToString(); + // } + // else if (value is IEnumerable> props) + // { + // if (Scope.Properties == null) + // Scope.Properties = new Dictionary(); + + // foreach (var pair in props) + // { + // Scope.Properties[pair.Key] = pair.Value; + // } + // } + // }, + // state); + + //} + //Provider.WriteLog(Info); + #endregion + } + } + + } +} diff --git a/src/SkyApm.Core/SkyLogging/SkyApmLoggerExtensions.cs b/src/SkyApm.Core/SkyLogging/SkyApmLoggerExtensions.cs new file mode 100644 index 00000000..de1d1c5c --- /dev/null +++ b/src/SkyApm.Core/SkyLogging/SkyApmLoggerExtensions.cs @@ -0,0 +1,36 @@ +锘縰sing Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Configuration; +using Microsoft.Extensions.Options; +using SkyApm.Core.Logging; +using System; + +namespace Microsoft.Extensions.DependencyInjection +{ + public static class SkyApmLoggerExtensions + { + static public ILoggingBuilder AddSkyApmLogger(this ILoggingBuilder builder) + { + builder.AddConfiguration(); + + builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton()); + builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton, SkyApmLoggerOptionsSetup>()); + builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton, LoggerProviderOptionsChangeTokenSource>()); + return builder; + } + + static public ILoggingBuilder AddSkyApmLogger(this ILoggingBuilder builder, Action configure) + { + if (configure == null) + { + throw new ArgumentNullException(nameof(configure)); + } + + builder.AddSkyApmLogger(); + builder.Services.Configure(configure); + + return builder; + } + } +} diff --git a/src/SkyApm.Core/SkyLogging/SkyApmLoggerOptionsSetup.cs b/src/SkyApm.Core/SkyLogging/SkyApmLoggerOptionsSetup.cs new file mode 100644 index 00000000..b04cb73c --- /dev/null +++ b/src/SkyApm.Core/SkyLogging/SkyApmLoggerOptionsSetup.cs @@ -0,0 +1,51 @@ +锘縰sing Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Configuration; +using Microsoft.Extensions.Options; + +namespace SkyApm.Core.Logging +{ + public class SkyApmLoggerOptionsSetup : ConfigureFromConfigurationOptions + { + public SkyApmLoggerOptionsSetup(ILoggerProviderConfiguration providerConfiguration) + : base(providerConfiguration.Configuration) + { + } + + } + + + public class FileLoggerOptions + { + string fFolder; + int fMaxFileSizeInMB; + int fRetainPolicyFileCount; + + public FileLoggerOptions() + { + } + + public LogLevel LogLevel { get; set; } = Microsoft.Extensions.Logging.LogLevel.Information; + + public string Folder + { + get + { + return !string.IsNullOrWhiteSpace(fFolder) ? + fFolder : System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location); + } + set { fFolder = value; } + } + + public int MaxFileSizeInMB + { + get { return fMaxFileSizeInMB > 0 ? fMaxFileSizeInMB : 2; } + set { fMaxFileSizeInMB = value; } + } + + public int RetainPolicyFileCount + { + get { return fRetainPolicyFileCount < 5 ? 5 : fRetainPolicyFileCount; } + set { fRetainPolicyFileCount = value; } + } + } +} diff --git a/src/SkyApm.Core/SkyLogging/SkyApmLoggerProvider.cs b/src/SkyApm.Core/SkyLogging/SkyApmLoggerProvider.cs new file mode 100644 index 00000000..16069687 --- /dev/null +++ b/src/SkyApm.Core/SkyLogging/SkyApmLoggerProvider.cs @@ -0,0 +1,101 @@ +锘縰sing Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using SkyApm.Tracing; +using SkyApm.Tracing.Segments; +using SkyApm.Transport; +using System; +using System.Collections.Concurrent; +using System.Threading.Tasks; + +namespace SkyApm.Core.Logging +{ + public class SkyApmLoggerProvider : IDisposable, ILoggerProvider, ISupportExternalScope + { + internal FileLoggerOptions Settings { get; private set; } + bool Terminated; + private readonly IEntrySegmentContextAccessor _entrySegmentContextAccessor; + ConcurrentQueue logQueues = new ConcurrentQueue(); + ConcurrentDictionary loggers = new ConcurrentDictionary(); + IExternalScopeProvider fScopeProvider; + protected IDisposable SettingsChangeToken; + private readonly ISkyApmLogDispatcher _skyApmLogDispatcher; + /// + /// + /// + public SkyApmLoggerProvider(FileLoggerOptions Settings, IServiceProvider serviceProvider) + { + _entrySegmentContextAccessor = serviceProvider.GetService(); + _skyApmLogDispatcher = serviceProvider.GetService(); + } + + public SkyApmLoggerProvider(IOptionsMonitor Settings, IServiceProvider serviceProvider) + : this(Settings.CurrentValue, serviceProvider) + { + SettingsChangeToken = Settings.OnChange(settings => + { + this.Settings = settings; + }); + } + + void ISupportExternalScope.SetScopeProvider(IExternalScopeProvider scopeProvider) + { + fScopeProvider = scopeProvider; + } + + ILogger ILoggerProvider.CreateLogger(string Category) + { + return loggers.GetOrAdd(Category, + (category) => + { + return new SkyApmLogger(this, _entrySegmentContextAccessor, _skyApmLogDispatcher, category); + }); + } + + protected virtual void Dispose(bool disposing) + { + if (SettingsChangeToken != null) + { + SettingsChangeToken.Dispose(); + SettingsChangeToken = null; + } + } + + internal IExternalScopeProvider ScopeProvider + { + get + { + if (fScopeProvider == null) + fScopeProvider = new LoggerExternalScopeProvider(); + return fScopeProvider; + } + } + + public bool IsDisposed { get; protected set; } + + ~SkyApmLoggerProvider() + { + if (!this.IsDisposed) + { + Dispose(false); + } + } + void IDisposable.Dispose() + { + if (!this.IsDisposed) + { + try + { + Dispose(true); + } + catch + { + } + + this.IsDisposed = true; + GC.SuppressFinalize(this); // instructs GC not bother to call the destructor + } + } + + } +} diff --git a/src/SkyApm.Core/Tracing/SegmentContextFactory.cs b/src/SkyApm.Core/Tracing/SegmentContextFactory.cs index 0394c701..45185e1e 100644 --- a/src/SkyApm.Core/Tracing/SegmentContextFactory.cs +++ b/src/SkyApm.Core/Tracing/SegmentContextFactory.cs @@ -78,7 +78,6 @@ public SegmentContext CreateEntrySegment(string operationName, ICarrier carrier, }; segmentContext.References.Add(segmentReference); } - _entrySegmentContextAccessor.Context = segmentContext; return segmentContext; } diff --git a/src/SkyApm.Core/Transport/AsyncQueueSkyApmLogDispatcher.cs b/src/SkyApm.Core/Transport/AsyncQueueSkyApmLogDispatcher.cs new file mode 100644 index 00000000..e9464323 --- /dev/null +++ b/src/SkyApm.Core/Transport/AsyncQueueSkyApmLogDispatcher.cs @@ -0,0 +1,87 @@ +锘縰sing SkyApm.Config; +using SkyApm.Logging; +using SkyApm.Tracing.Segments; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace SkyApm.Transport +{ + public class AsyncQueueSkyApmLogDispatcher : ISkyApmLogDispatcher + { + private readonly ILogger _logger; + private readonly CancellationTokenSource _cancellation; + + private readonly ConcurrentQueue _segmentQueue; + + private readonly IRuntimeEnvironment _runtimeEnvironment; + + private readonly ILoggerReporter _loggerReporter; + + private readonly ILoggerContextContextMapper _loggerContextContextMapper; + + private readonly TransportConfig _config; + + private int _offset; + + public AsyncQueueSkyApmLogDispatcher(IConfigAccessor configAccessor, ILoggerFactory loggerFactory, ILoggerContextContextMapper loggerContextContextMapper, ILoggerReporter loggerReporter, IRuntimeEnvironment runtimeEnvironment) + { + _logger = loggerFactory.CreateLogger(typeof(AsyncQueueSkyApmLogDispatcher)); + _config = configAccessor.Get(); + _loggerContextContextMapper = loggerContextContextMapper; + _runtimeEnvironment = runtimeEnvironment; + _segmentQueue = new ConcurrentQueue(); + _cancellation = new CancellationTokenSource(); + _loggerReporter= loggerReporter; + } + + public bool Dispatch(LoggerContext loggerContext) + { + if (!_runtimeEnvironment.Initialized || loggerContext == null) + return false; + + // todo performance optimization for ConcurrentQueue + if (_config.QueueSize < _offset || _cancellation.IsCancellationRequested) + return false; + + var segment = _loggerContextContextMapper.Map(loggerContext); + + if (segment == null) + return false; + + _segmentQueue.Enqueue(segment); + + Interlocked.Increment(ref _offset); + + _logger.Debug($"Dispatch trace segment. [SegmentId]={loggerContext.SegmentContext.SegmentId}."); + return true; + } + + public Task Flush(CancellationToken token = default) + { + var limit = _config.BatchSize; + var index = 0; + var logges = new List(limit); + while (index++ < limit && _segmentQueue.TryDequeue(out var request)) + { + logges.Add(request); + Interlocked.Decrement(ref _offset); + } + + // send async + if (logges.Count > 0) + { + _loggerReporter.ReportAsync(logges, token); + } + + Interlocked.Exchange(ref _offset, _segmentQueue.Count); + + return Task.CompletedTask; + } + public void Close() + { + _cancellation.Cancel(); + } + } +} diff --git a/src/SkyApm.Core/Transport/LoggerContextContextMapper.cs b/src/SkyApm.Core/Transport/LoggerContextContextMapper.cs new file mode 100644 index 00000000..942fae2d --- /dev/null +++ b/src/SkyApm.Core/Transport/LoggerContextContextMapper.cs @@ -0,0 +1,24 @@ +锘縰sing SkyApm.Tracing.Segments; + +namespace SkyApm.Transport +{ + public class LoggerContextContextMapper : ILoggerContextContextMapper + { + private readonly ISegmentContextMapper _segmentContextMapper; + + public LoggerContextContextMapper(ISegmentContextMapper segmentContextMapper) + { + _segmentContextMapper = segmentContextMapper; + } + + public LoggerRequest Map(LoggerContext loggerContext) + { + var segmentRequest = _segmentContextMapper.Map(loggerContext.SegmentContext); + return new LoggerRequest + { + Logs = loggerContext.Logs, + SegmentRequest = segmentRequest, + }; + } + } +} diff --git a/src/SkyApm.Transport.Grpc/Common/SegmentV8Helpers.cs b/src/SkyApm.Transport.Grpc/Common/SegmentV8Helpers.cs index 13f96b84..38802faa 100644 --- a/src/SkyApm.Transport.Grpc/Common/SegmentV8Helpers.cs +++ b/src/SkyApm.Transport.Grpc/Common/SegmentV8Helpers.cs @@ -20,7 +20,11 @@ using System.Linq; using Google.Protobuf; using SkyApm.Common; +using SkyApm.Tracing.Segments; using SkyWalking.NetworkProtocol.V3; +using SegmentReference = SkyWalking.NetworkProtocol.V3.SegmentReference; +using SpanLayer = SkyWalking.NetworkProtocol.V3.SpanLayer; +using SpanType = SkyWalking.NetworkProtocol.V3.SpanType; namespace SkyApm.Transport.Grpc.Common { @@ -67,7 +71,7 @@ private static SpanObject MapToSpan(SpanRequest request) private static SegmentReference MapToSegmentReference(SegmentReferenceRequest referenceRequest) { - var reference = new SegmentReference + var reference = new SkyWalking.NetworkProtocol.V3.SegmentReference { TraceId = referenceRequest.TraceId, ParentService = referenceRequest.ParentServiceId, diff --git a/src/SkyApm.Transport.Grpc/V8/LoggerReporter.cs b/src/SkyApm.Transport.Grpc/V8/LoggerReporter.cs new file mode 100644 index 00000000..960f57dc --- /dev/null +++ b/src/SkyApm.Transport.Grpc/V8/LoggerReporter.cs @@ -0,0 +1,91 @@ +锘縰sing SkyApm.Config; +using SkyApm.Logging; +using SkyWalking.NetworkProtocol.V3; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace SkyApm.Transport.Grpc +{ + public class LoggerReporter : ILoggerReporter + { + + private readonly ConnectionManager _connectionManager; + private readonly ILogger _logger; + private readonly GrpcConfig _config; + + public LoggerReporter(ConnectionManager connectionManager, IConfigAccessor configAccessor, + ILoggerFactory loggerFactory) + { + _connectionManager = connectionManager; + _config = configAccessor.Get(); + _logger = loggerFactory.CreateLogger(typeof(SegmentReporter)); + } + + + public async Task ReportAsync(IReadOnlyCollection loggerRequests, CancellationToken cancellationToken = default) + { + if (!_connectionManager.Ready) + { + return; + } + + var connection = _connectionManager.GetConnection(); + try + { + var stopwatch = Stopwatch.StartNew(); + var client = new LogReportService.LogReportServiceClient(connection); + using (var asyncClientStreamingCall = client.collect(_config.GetMeta(), _config.GetReportTimeout(), cancellationToken)) + { + foreach (var loggerRequest in loggerRequests) + { + StringBuilder logmessage=new StringBuilder(); + foreach (var log in loggerRequest.Logs) + { + logmessage.Append($"\r\n{log.Key}:{log.Value}"); + } + var logbody = new LogData() + { + TraceContext = new TraceContext() + { + TraceId = loggerRequest.SegmentRequest.TraceId, + TraceSegmentId = loggerRequest.SegmentRequest.Segment.SegmentId, + //SpanId=item.Segment + }, + Timestamp = DateTimeOffset.UtcNow.Ticks, + Service = loggerRequest.SegmentRequest.Segment.ServiceId, + ServiceInstance = loggerRequest.SegmentRequest.Segment.ServiceInstanceId, + Endpoint = "", + Body = new LogDataBody() + { + Type = "text", + Text = new TextLog() + { + Text = logmessage.ToString(), + }, + }, + }; + await asyncClientStreamingCall.RequestStream.WriteAsync(logbody); + } + + await asyncClientStreamingCall.RequestStream.CompleteAsync(); + await asyncClientStreamingCall.ResponseAsync; + + stopwatch.Stop(); + _logger.Information($"Report {loggerRequests.Count} logger logger. cost: {stopwatch.Elapsed}s"); + } + + } + catch (Exception ex) + { + _logger.Error("Report trace segment fail.", ex); + _connectionManager.Failure(ex); + + } + + } + } +} diff --git a/src/SkyApm.Transport.Grpc/V8/SegmentReporter.cs b/src/SkyApm.Transport.Grpc/V8/SegmentReporter.cs index bfb9ed1e..74e4ae95 100644 --- a/src/SkyApm.Transport.Grpc/V8/SegmentReporter.cs +++ b/src/SkyApm.Transport.Grpc/V8/SegmentReporter.cs @@ -65,6 +65,43 @@ public async Task ReportAsync(IReadOnlyCollection segmentRequest await asyncClientStreamingCall.ResponseAsync; } + + //var client1 = new LogReportService.LogReportServiceClient(connection); + //using (var asyncClientStreamingCall = client1.collect(_config.GetMeta(), _config.GetReportTimeout(), cancellationToken)) + //{ + // foreach (var item in segmentRequests) + // { + // var logbody = new LogData() + // { + // TraceContext=new TraceContext() + // { + // TraceId=item.TraceId, + // TraceSegmentId=item.Segment.SegmentId, + // //SpanId=item.Segment + // }, + // Timestamp = DateTimeOffset.UtcNow.Ticks, + // Service = item.Segment.ServiceId, + // ServiceInstance = item.Segment.ServiceInstanceId, + // Endpoint = "", + // Body = new LogDataBody() + // { + // Type = "json", + // Json = new JSONLog() + // { + // Json = "测试日志", + // }, + // }, + // }; + // await asyncClientStreamingCall.RequestStream.WriteAsync(logbody); + // } + + // await asyncClientStreamingCall.RequestStream.CompleteAsync(); + // await asyncClientStreamingCall.ResponseAsync; + //} + + + + stopwatch.Stop(); _logger.Information($"Report {segmentRequests.Count} trace segment. cost: {stopwatch.Elapsed}s"); } From b953b064eff6efda1ac7c176656b6f4ab94633cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B3=BD=E5=A8=81=20=E7=8E=8B?= <1585955375@qq.com> Date: Thu, 21 Apr 2022 13:56:45 +0800 Subject: [PATCH 2/6] feat : Remove MSLogger, implementation SkyApm.ILogger, Add Extension for AddPushSkyApmLogger --- .../Controllers/WeatherForecastController.cs | 8 +- sample/Sky.Apm.Sample.Logging/Program.cs | 5 +- .../Config/LogPushSkywalkingConfig.cs | 11 ++ .../Logging/ILoggerFactory.cs | 1 + .../SkyApmHostingStartup.cs | 6 +- .../Extensions/ServiceCollectionExtensions.cs | 17 +++ src/SkyApm.Core/Logging/NullLoggerFactory.cs | 5 + src/SkyApm.Core/SkyApm.Core.csproj | 3 - src/SkyApm.Core/SkyLogging/SkyApmLogger.cs | 129 ------------------ .../SkyLogging/SkyApmLoggerExtensions.cs | 36 ----- .../SkyLogging/SkyApmLoggerOptionsSetup.cs | 51 ------- .../SkyLogging/SkyApmLoggerProvider.cs | 101 -------------- .../V8/LoggerReporter.cs | 2 +- .../DefaultLoggerFactory.cs | 13 +- src/SkyApm.Utilities.Logging/SkyApmLogger.cs | 68 +++++++++ 15 files changed, 120 insertions(+), 336 deletions(-) create mode 100644 src/SkyApm.Abstractions/Config/LogPushSkywalkingConfig.cs delete mode 100644 src/SkyApm.Core/SkyLogging/SkyApmLogger.cs delete mode 100644 src/SkyApm.Core/SkyLogging/SkyApmLoggerExtensions.cs delete mode 100644 src/SkyApm.Core/SkyLogging/SkyApmLoggerOptionsSetup.cs delete mode 100644 src/SkyApm.Core/SkyLogging/SkyApmLoggerProvider.cs create mode 100644 src/SkyApm.Utilities.Logging/SkyApmLogger.cs diff --git a/sample/Sky.Apm.Sample.Logging/Controllers/WeatherForecastController.cs b/sample/Sky.Apm.Sample.Logging/Controllers/WeatherForecastController.cs index 4ab5889a..4ddb593a 100644 --- a/sample/Sky.Apm.Sample.Logging/Controllers/WeatherForecastController.cs +++ b/sample/Sky.Apm.Sample.Logging/Controllers/WeatherForecastController.cs @@ -13,10 +13,10 @@ public class WeatherForecastController : ControllerBase }; private readonly Test _test; - private readonly ILogger _logger; - public WeatherForecastController(ILogger logger, Test test) + private readonly SkyApm.Logging.ILogger _loggerFactory; + public WeatherForecastController(SkyApm.Logging.ILoggerFactory loggerFactory, Test test) { - _logger = logger; + _loggerFactory = loggerFactory.CreateSkyApmLogger(GetType()); _test = test; } @@ -24,7 +24,7 @@ public WeatherForecastController(ILogger logger, Test public IEnumerable Get() { //Console.WriteLine(_entrySegmentContextAccessor.Context?.TraceId); - _logger.LogInformation("我用来测试自定义日志!!!!!!!!!!!!"); + _loggerFactory.Information("qiwnkasdnaskndlaknd laksndk asndkas ndl nsald nlasdn la!!!!!!!!!!!!"); _test.Create(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { diff --git a/sample/Sky.Apm.Sample.Logging/Program.cs b/sample/Sky.Apm.Sample.Logging/Program.cs index d0ae32d6..5810f764 100644 --- a/sample/Sky.Apm.Sample.Logging/Program.cs +++ b/sample/Sky.Apm.Sample.Logging/Program.cs @@ -11,10 +11,7 @@ builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.AddScoped(); -//builder.Services.AddLogging(logging => -//{ -// logging.AddSkyApmLogger(); -//}); +builder.Services.AddPushSkyApmLogger(x => x.Enable = false); var app = builder.Build(); // Configure the HTTP request pipeline. diff --git a/src/SkyApm.Abstractions/Config/LogPushSkywalkingConfig.cs b/src/SkyApm.Abstractions/Config/LogPushSkywalkingConfig.cs new file mode 100644 index 00000000..1ffd2f91 --- /dev/null +++ b/src/SkyApm.Abstractions/Config/LogPushSkywalkingConfig.cs @@ -0,0 +1,11 @@ +锘縰sing System; +using System.Collections.Generic; +using System.Text; + +namespace SkyApm.Config +{ + public class LogPushSkywalkingConfig + { + public bool Enable { get; set; } + } +} diff --git a/src/SkyApm.Abstractions/Logging/ILoggerFactory.cs b/src/SkyApm.Abstractions/Logging/ILoggerFactory.cs index aee68fbc..e16d01a2 100644 --- a/src/SkyApm.Abstractions/Logging/ILoggerFactory.cs +++ b/src/SkyApm.Abstractions/Logging/ILoggerFactory.cs @@ -23,5 +23,6 @@ namespace SkyApm.Logging public interface ILoggerFactory { ILogger CreateLogger(Type type); + SkyApm.Logging.ILogger CreateSkyApmLogger(Type type); } } \ No newline at end of file diff --git a/src/SkyApm.Agent.AspNetCore/SkyApmHostingStartup.cs b/src/SkyApm.Agent.AspNetCore/SkyApmHostingStartup.cs index 39ad0b32..5adc7b2e 100644 --- a/src/SkyApm.Agent.AspNetCore/SkyApmHostingStartup.cs +++ b/src/SkyApm.Agent.AspNetCore/SkyApmHostingStartup.cs @@ -29,11 +29,7 @@ internal class SkyApmHostingStartup : IHostingStartup { public void Configure(IWebHostBuilder builder) { - builder.ConfigureServices(services => services.AddSkyAPM(ext => ext.AddAspNetCoreHosting()) - .AddLogging(logging => - { - logging.AddSkyApmLogger(); - })); + builder.ConfigureServices(services => services.AddSkyAPM(ext => ext.AddAspNetCoreHosting())); } } } \ No newline at end of file diff --git a/src/SkyApm.Agent.Hosting/Extensions/ServiceCollectionExtensions.cs b/src/SkyApm.Agent.Hosting/Extensions/ServiceCollectionExtensions.cs index 5bf47fc3..21f366db 100644 --- a/src/SkyApm.Agent.Hosting/Extensions/ServiceCollectionExtensions.cs +++ b/src/SkyApm.Agent.Hosting/Extensions/ServiceCollectionExtensions.cs @@ -47,6 +47,22 @@ public static IServiceCollection AddSkyAPM(this IServiceCollection services, Act return services; } + public static IServiceCollection AddPushSkyApmLogger(this IServiceCollection services,Action action) + { + if (services == null) + { + throw new ArgumentNullException(nameof(services)); + } + if (action == null) + { + throw new ArgumentNullException(nameof(action)); + } + LogPushSkywalkingConfig logPushSkywalking=new LogPushSkywalkingConfig(); + action.Invoke(logPushSkywalking); + services.Configure(action); + return services; + } + internal static IServiceCollection AddSkyAPMCore(this IServiceCollection services, Action extensionsSetup = null) { if (services == null) @@ -130,5 +146,6 @@ private static IServiceCollection AddSkyApmLogging(this IServiceCollection servi services.AddSingleton(); return services; } + } } \ No newline at end of file diff --git a/src/SkyApm.Core/Logging/NullLoggerFactory.cs b/src/SkyApm.Core/Logging/NullLoggerFactory.cs index 7320003f..4d38934e 100644 --- a/src/SkyApm.Core/Logging/NullLoggerFactory.cs +++ b/src/SkyApm.Core/Logging/NullLoggerFactory.cs @@ -26,5 +26,10 @@ public ILogger CreateLogger(Type type) { return new NullLogger(); } + + public ILogger CreateSkyApmLogger(Type type) + { + throw new NotImplementedException(); + } } } \ No newline at end of file diff --git a/src/SkyApm.Core/SkyApm.Core.csproj b/src/SkyApm.Core/SkyApm.Core.csproj index 2d57777a..2ca89fc1 100644 --- a/src/SkyApm.Core/SkyApm.Core.csproj +++ b/src/SkyApm.Core/SkyApm.Core.csproj @@ -19,9 +19,6 @@ --> - - - diff --git a/src/SkyApm.Core/SkyLogging/SkyApmLogger.cs b/src/SkyApm.Core/SkyLogging/SkyApmLogger.cs deleted file mode 100644 index 980e917b..00000000 --- a/src/SkyApm.Core/SkyLogging/SkyApmLogger.cs +++ /dev/null @@ -1,129 +0,0 @@ -锘縰sing Microsoft.Extensions.Logging; -using SkyApm.Tracing; -using SkyApm.Tracing.Segments; -using SkyApm.Transport; -using System; -using System.Collections.Generic; - -namespace SkyApm.Core.Logging -{ - public class SkyApmLogger : ILogger - { - - public SkyApmLoggerProvider Provider { get; private set; } - public string Category { get; private set; } - private readonly IEntrySegmentContextAccessor _entrySegmentContextAccessor; - - private readonly ISkyApmLogDispatcher _skyApmLogDispatcher; - public SkyApmLogger(SkyApmLoggerProvider Provider, IEntrySegmentContextAccessor entrySegmentContextAccessor, ISkyApmLogDispatcher skyApmLogDispatcher, string Category) - { - this.Provider = Provider; - _entrySegmentContextAccessor = entrySegmentContextAccessor; - this.Category = Category; - _skyApmLogDispatcher = skyApmLogDispatcher; - } - - IDisposable ILogger.BeginScope(TState state) - { - return Provider.ScopeProvider.Push(state); - } - - bool ILogger.IsEnabled(LogLevel logLevel) - { - return logLevel != LogLevel.None; - } - - void ILogger.Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter) - { - if ((this as ILogger).IsEnabled(logLevel)) - { - var logs = new Dictionary(); - logs.Add("className", this.Category); - logs.Add("Level", logLevel); - logs.Add("logMessage", exception?.Message ?? state.ToString()); - logs.Add("eventId", eventId.ToString()); - logs.Add("state", state.ToString()); - if (state is string) - { - logs.Add("stateText", state.ToString()); - } - else if (state is IEnumerable> Properties) - { - var stateProperties = new Dictionary(); - foreach (KeyValuePair item in Properties) - { - stateProperties.Add(item.Key, item.Value); - } - logs.Add("stateProperties", stateProperties); - } - var logContext = new LoggerContext() - { - Logs = logs, - SegmentContext = _entrySegmentContextAccessor.Context, - }; - _skyApmLogDispatcher.Dispatch(logContext); - #region MyRegion - - - //SkyApmLogEntry Info = new SkyApmLogEntry(); - //Info.Category = this.Category; - //Info.Level = logLevel.ToString(); - //Info.Text = exception?.Message ?? state.ToString(); // formatter(state, exception) - //Info.Exception = exception; - //Info.EventId = eventId; - //Info.State = state; - - //// well, you never know what it really is - //if (state is string) - //{ - // Info.StateText = state.ToString(); - //} - //// in case we have to do with a message template, lets get the keys and values (for Structured Logging providers) - //// SEE: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging#log-message-template - //// SEE: https://softwareengineering.stackexchange.com/questions/312197/benefits-of-structured-logging-vs-basic-logging - //else if (state is IEnumerable> Properties) - //{ - // Info.StateProperties = new Dictionary(); - - // foreach (KeyValuePair item in Properties) - // { - // Info.StateProperties[item.Key] = item.Value; - // } - //} - - // gather info about scope(s), if any - //if (Provider.ScopeProvider != null) - //{ - // Provider.ScopeProvider.ForEachScope((value, loggingProps) => - // { - // if (Info.Scopes == null) - // Info.Scopes = new List(); - - // LogScopeInfo Scope = new LogScopeInfo(); - // Info.Scopes.Add(Scope); - - // if (value is string) - // { - // Scope.Text = value.ToString(); - // } - // else if (value is IEnumerable> props) - // { - // if (Scope.Properties == null) - // Scope.Properties = new Dictionary(); - - // foreach (var pair in props) - // { - // Scope.Properties[pair.Key] = pair.Value; - // } - // } - // }, - // state); - - //} - //Provider.WriteLog(Info); - #endregion - } - } - - } -} diff --git a/src/SkyApm.Core/SkyLogging/SkyApmLoggerExtensions.cs b/src/SkyApm.Core/SkyLogging/SkyApmLoggerExtensions.cs deleted file mode 100644 index de1d1c5c..00000000 --- a/src/SkyApm.Core/SkyLogging/SkyApmLoggerExtensions.cs +++ /dev/null @@ -1,36 +0,0 @@ -锘縰sing Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Logging.Configuration; -using Microsoft.Extensions.Options; -using SkyApm.Core.Logging; -using System; - -namespace Microsoft.Extensions.DependencyInjection -{ - public static class SkyApmLoggerExtensions - { - static public ILoggingBuilder AddSkyApmLogger(this ILoggingBuilder builder) - { - builder.AddConfiguration(); - - builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton()); - builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton, SkyApmLoggerOptionsSetup>()); - builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton, LoggerProviderOptionsChangeTokenSource>()); - return builder; - } - - static public ILoggingBuilder AddSkyApmLogger(this ILoggingBuilder builder, Action configure) - { - if (configure == null) - { - throw new ArgumentNullException(nameof(configure)); - } - - builder.AddSkyApmLogger(); - builder.Services.Configure(configure); - - return builder; - } - } -} diff --git a/src/SkyApm.Core/SkyLogging/SkyApmLoggerOptionsSetup.cs b/src/SkyApm.Core/SkyLogging/SkyApmLoggerOptionsSetup.cs deleted file mode 100644 index b04cb73c..00000000 --- a/src/SkyApm.Core/SkyLogging/SkyApmLoggerOptionsSetup.cs +++ /dev/null @@ -1,51 +0,0 @@ -锘縰sing Microsoft.Extensions.Logging; -using Microsoft.Extensions.Logging.Configuration; -using Microsoft.Extensions.Options; - -namespace SkyApm.Core.Logging -{ - public class SkyApmLoggerOptionsSetup : ConfigureFromConfigurationOptions - { - public SkyApmLoggerOptionsSetup(ILoggerProviderConfiguration providerConfiguration) - : base(providerConfiguration.Configuration) - { - } - - } - - - public class FileLoggerOptions - { - string fFolder; - int fMaxFileSizeInMB; - int fRetainPolicyFileCount; - - public FileLoggerOptions() - { - } - - public LogLevel LogLevel { get; set; } = Microsoft.Extensions.Logging.LogLevel.Information; - - public string Folder - { - get - { - return !string.IsNullOrWhiteSpace(fFolder) ? - fFolder : System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location); - } - set { fFolder = value; } - } - - public int MaxFileSizeInMB - { - get { return fMaxFileSizeInMB > 0 ? fMaxFileSizeInMB : 2; } - set { fMaxFileSizeInMB = value; } - } - - public int RetainPolicyFileCount - { - get { return fRetainPolicyFileCount < 5 ? 5 : fRetainPolicyFileCount; } - set { fRetainPolicyFileCount = value; } - } - } -} diff --git a/src/SkyApm.Core/SkyLogging/SkyApmLoggerProvider.cs b/src/SkyApm.Core/SkyLogging/SkyApmLoggerProvider.cs deleted file mode 100644 index 16069687..00000000 --- a/src/SkyApm.Core/SkyLogging/SkyApmLoggerProvider.cs +++ /dev/null @@ -1,101 +0,0 @@ -锘縰sing Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; -using SkyApm.Tracing; -using SkyApm.Tracing.Segments; -using SkyApm.Transport; -using System; -using System.Collections.Concurrent; -using System.Threading.Tasks; - -namespace SkyApm.Core.Logging -{ - public class SkyApmLoggerProvider : IDisposable, ILoggerProvider, ISupportExternalScope - { - internal FileLoggerOptions Settings { get; private set; } - bool Terminated; - private readonly IEntrySegmentContextAccessor _entrySegmentContextAccessor; - ConcurrentQueue logQueues = new ConcurrentQueue(); - ConcurrentDictionary loggers = new ConcurrentDictionary(); - IExternalScopeProvider fScopeProvider; - protected IDisposable SettingsChangeToken; - private readonly ISkyApmLogDispatcher _skyApmLogDispatcher; - /// - /// - /// - public SkyApmLoggerProvider(FileLoggerOptions Settings, IServiceProvider serviceProvider) - { - _entrySegmentContextAccessor = serviceProvider.GetService(); - _skyApmLogDispatcher = serviceProvider.GetService(); - } - - public SkyApmLoggerProvider(IOptionsMonitor Settings, IServiceProvider serviceProvider) - : this(Settings.CurrentValue, serviceProvider) - { - SettingsChangeToken = Settings.OnChange(settings => - { - this.Settings = settings; - }); - } - - void ISupportExternalScope.SetScopeProvider(IExternalScopeProvider scopeProvider) - { - fScopeProvider = scopeProvider; - } - - ILogger ILoggerProvider.CreateLogger(string Category) - { - return loggers.GetOrAdd(Category, - (category) => - { - return new SkyApmLogger(this, _entrySegmentContextAccessor, _skyApmLogDispatcher, category); - }); - } - - protected virtual void Dispose(bool disposing) - { - if (SettingsChangeToken != null) - { - SettingsChangeToken.Dispose(); - SettingsChangeToken = null; - } - } - - internal IExternalScopeProvider ScopeProvider - { - get - { - if (fScopeProvider == null) - fScopeProvider = new LoggerExternalScopeProvider(); - return fScopeProvider; - } - } - - public bool IsDisposed { get; protected set; } - - ~SkyApmLoggerProvider() - { - if (!this.IsDisposed) - { - Dispose(false); - } - } - void IDisposable.Dispose() - { - if (!this.IsDisposed) - { - try - { - Dispose(true); - } - catch - { - } - - this.IsDisposed = true; - GC.SuppressFinalize(this); // instructs GC not bother to call the destructor - } - } - - } -} diff --git a/src/SkyApm.Transport.Grpc/V8/LoggerReporter.cs b/src/SkyApm.Transport.Grpc/V8/LoggerReporter.cs index 960f57dc..f075e23f 100644 --- a/src/SkyApm.Transport.Grpc/V8/LoggerReporter.cs +++ b/src/SkyApm.Transport.Grpc/V8/LoggerReporter.cs @@ -45,7 +45,7 @@ public async Task ReportAsync(IReadOnlyCollection loggerRequests, StringBuilder logmessage=new StringBuilder(); foreach (var log in loggerRequest.Logs) { - logmessage.Append($"\r\n{log.Key}:{log.Value}"); + logmessage.Append($"\r\n{log.Key} : {log.Value}"); } var logbody = new LogData() { diff --git a/src/SkyApm.Utilities.Logging/DefaultLoggerFactory.cs b/src/SkyApm.Utilities.Logging/DefaultLoggerFactory.cs index e2f3e827..20331e4e 100644 --- a/src/SkyApm.Utilities.Logging/DefaultLoggerFactory.cs +++ b/src/SkyApm.Utilities.Logging/DefaultLoggerFactory.cs @@ -24,6 +24,7 @@ using ILogger = SkyApm.Logging.ILogger; using ILoggerFactory = SkyApm.Logging.ILoggerFactory; using MSLoggerFactory = Microsoft.Extensions.Logging.LoggerFactory; +using Microsoft.Extensions.Options; namespace SkyApm.Utilities.Logging { @@ -34,10 +35,13 @@ public class DefaultLoggerFactory : SkyApm.Logging.ILoggerFactory private readonly MSLoggerFactory _loggerFactory; private readonly LoggingConfig _loggingConfig; - - public DefaultLoggerFactory(IConfigAccessor configAccessor) + private readonly IServiceProvider _serviceProvider; + private readonly IOptions _logPushSkywalkingConfig; + public DefaultLoggerFactory(IConfigAccessor configAccessor, IServiceProvider serviceProvider, IOptions logPushSkywalkingConfig) { + _serviceProvider= serviceProvider; _loggingConfig = configAccessor.Get(); + _logPushSkywalkingConfig = logPushSkywalkingConfig; _loggerFactory = new MSLoggerFactory(); var instrumentationConfig = configAccessor.Get(); @@ -56,6 +60,11 @@ public SkyApm.Logging.ILogger CreateLogger(Type type) return new DefaultLogger(_loggerFactory.CreateLogger(type)); } + public SkyApm.Logging.ILogger CreateSkyApmLogger(Type type) + { + return new SkyApmLogger(type, _serviceProvider, _logPushSkywalkingConfig.Value.Enable); + } + private static LogEventLevel EventLevel(string level) { return LogEventLevel.TryParse(level, out var logEventLevel) diff --git a/src/SkyApm.Utilities.Logging/SkyApmLogger.cs b/src/SkyApm.Utilities.Logging/SkyApmLogger.cs new file mode 100644 index 00000000..2a3c5aac --- /dev/null +++ b/src/SkyApm.Utilities.Logging/SkyApmLogger.cs @@ -0,0 +1,68 @@ +锘縰sing Microsoft.Extensions.DependencyInjection; +using SkyApm.Logging; +using SkyApm.Tracing; +using SkyApm.Tracing.Segments; +using SkyApm.Transport; +using System; +using System.Collections.Generic; + +namespace SkyApm.Utilities.Logging +{ + public class SkyApmLogger : ILogger + { + private readonly Type _loggerName; + private readonly IEntrySegmentContextAccessor _entrySegmentContextAccessor; + private readonly ISkyApmLogDispatcher _skyApmLogDispatcher; + private readonly bool _pushSkywalking; + public SkyApmLogger(Type type, IServiceProvider serviceProvider,bool pushSkywalking) + { + _entrySegmentContextAccessor = serviceProvider.GetService(); + _skyApmLogDispatcher = serviceProvider.GetService(); + _loggerName = type; + _pushSkywalking= pushSkywalking; + } + + public void Debug(string message) + { + SendLog("Debug", message); + } + + public void Error(string message, Exception exception) + { + SendLog("Error", message); + } + + public void Information(string message) + { + SendLog("Information", message); + } + + public void Trace(string message) + { + SendLog("Trace", message); + } + + public void Warning(string message) + { + SendLog("Warning", message); + } + + private void SendLog(string logLevel, string message) + { + if(_pushSkywalking) + { + var logs = new Dictionary(); + logs.Add("className", _loggerName); + logs.Add("Level", logLevel); + logs.Add("logMessage", message); + var logContext = new LoggerContext() + { + Logs = logs, + SegmentContext = _entrySegmentContextAccessor.Context, + }; + _skyApmLogDispatcher.Dispatch(logContext); + } + + } + } +} From 580cf2e45450ef53edf084d6e4a153d130870fd1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B3=BD=E5=A8=81=20=E7=8E=8B?= <1585955375@qq.com> Date: Wed, 27 Apr 2022 21:41:53 +0800 Subject: [PATCH 3/6] feat : add a copyright header to all new files --- .../Controllers/WeatherForecastController.cs | 20 ++++++++++++++++++- sample/Sky.Apm.Sample.Logging/Program.cs | 19 ++++++++++++++++-- sample/Sky.Apm.Sample.Logging/Test.cs | 20 ++++++++++++++++++- .../Sky.Apm.Sample.Logging/WeatherForecast.cs | 18 +++++++++++++++++ .../Transport/ILoggerContextContextMapper.cs | 20 ++++++++++++++++++- .../Transport/ILoggerReporter.cs | 20 ++++++++++++++++++- .../Transport/ISkyApmLogDispatcher.cs | 20 ++++++++++++++++++- .../Transport/LoggerRequest.cs | 20 ++++++++++++++++++- .../AsyncQueueSkyApmLogDispatcher.cs | 20 ++++++++++++++++++- .../Transport/LoggerContextContextMapper.cs | 20 ++++++++++++++++++- .../V8/LoggerReporter.cs | 20 ++++++++++++++++++- src/SkyApm.Utilities.Logging/SkyApmLogger.cs | 20 ++++++++++++++++++- 12 files changed, 225 insertions(+), 12 deletions(-) diff --git a/sample/Sky.Apm.Sample.Logging/Controllers/WeatherForecastController.cs b/sample/Sky.Apm.Sample.Logging/Controllers/WeatherForecastController.cs index 4ddb593a..c3e86912 100644 --- a/sample/Sky.Apm.Sample.Logging/Controllers/WeatherForecastController.cs +++ b/sample/Sky.Apm.Sample.Logging/Controllers/WeatherForecastController.cs @@ -1,3 +1,21 @@ +/* + * Licensed to the SkyAPM under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The SkyAPM licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + using Microsoft.AspNetCore.Mvc; using SkyApm.Tracing; @@ -24,7 +42,7 @@ public WeatherForecastController(SkyApm.Logging.ILoggerFactory loggerFactory, Te public IEnumerable Get() { //Console.WriteLine(_entrySegmentContextAccessor.Context?.TraceId); - _loggerFactory.Information("qiwnkasdnaskndlaknd laksndk asndkas ndl nsald nlasdn la!!!!!!!!!!!!"); + _loggerFactory.Information("qiwnkasdnaskndlaknd laksndk asndkas ndl nsald nlasdn la锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷"); _test.Create(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { diff --git a/sample/Sky.Apm.Sample.Logging/Program.cs b/sample/Sky.Apm.Sample.Logging/Program.cs index 5810f764..7e5d4b78 100644 --- a/sample/Sky.Apm.Sample.Logging/Program.cs +++ b/sample/Sky.Apm.Sample.Logging/Program.cs @@ -1,5 +1,20 @@ -//using Sky.Apm.Sample.Logging.Test; - +/* + * Licensed to the SkyAPM under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The SkyAPM licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ using Sky.Apm.Sample.Logging; var builder = WebApplication.CreateBuilder(args); diff --git a/sample/Sky.Apm.Sample.Logging/Test.cs b/sample/Sky.Apm.Sample.Logging/Test.cs index d2fe7c57..70f1394d 100644 --- a/sample/Sky.Apm.Sample.Logging/Test.cs +++ b/sample/Sky.Apm.Sample.Logging/Test.cs @@ -1,4 +1,22 @@ -锘縩amespace Sky.Apm.Sample.Logging +锘/* + * Licensed to the SkyAPM under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The SkyAPM licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +namespace Sky.Apm.Sample.Logging { public class Test { diff --git a/sample/Sky.Apm.Sample.Logging/WeatherForecast.cs b/sample/Sky.Apm.Sample.Logging/WeatherForecast.cs index d3164cf5..84dd98e0 100644 --- a/sample/Sky.Apm.Sample.Logging/WeatherForecast.cs +++ b/sample/Sky.Apm.Sample.Logging/WeatherForecast.cs @@ -1,3 +1,21 @@ +/* + * Licensed to the SkyAPM under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The SkyAPM licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + namespace Sky.Apm.Sample.Logging { public class WeatherForecast diff --git a/src/SkyApm.Abstractions/Transport/ILoggerContextContextMapper.cs b/src/SkyApm.Abstractions/Transport/ILoggerContextContextMapper.cs index a5894d93..da7efdfc 100644 --- a/src/SkyApm.Abstractions/Transport/ILoggerContextContextMapper.cs +++ b/src/SkyApm.Abstractions/Transport/ILoggerContextContextMapper.cs @@ -1,4 +1,22 @@ -锘縰sing SkyApm.Tracing.Segments; +锘/* + * Licensed to the SkyAPM under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The SkyAPM licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +using SkyApm.Tracing.Segments; namespace SkyApm.Transport { public interface ILoggerContextContextMapper diff --git a/src/SkyApm.Abstractions/Transport/ILoggerReporter.cs b/src/SkyApm.Abstractions/Transport/ILoggerReporter.cs index cab7265b..66fd3ba6 100644 --- a/src/SkyApm.Abstractions/Transport/ILoggerReporter.cs +++ b/src/SkyApm.Abstractions/Transport/ILoggerReporter.cs @@ -1,4 +1,22 @@ -锘縰sing System; +锘/* + * Licensed to the SkyAPM under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The SkyAPM licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +using System; using System.Collections.Generic; using System.Text; using System.Threading; diff --git a/src/SkyApm.Abstractions/Transport/ISkyApmLogDispatcher.cs b/src/SkyApm.Abstractions/Transport/ISkyApmLogDispatcher.cs index f9e9d982..8925a3a6 100644 --- a/src/SkyApm.Abstractions/Transport/ISkyApmLogDispatcher.cs +++ b/src/SkyApm.Abstractions/Transport/ISkyApmLogDispatcher.cs @@ -1,4 +1,22 @@ -锘縰sing SkyApm.Tracing.Segments; +锘/* + * Licensed to the SkyAPM under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The SkyAPM licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +using SkyApm.Tracing.Segments; using System.Threading; using System.Threading.Tasks; diff --git a/src/SkyApm.Abstractions/Transport/LoggerRequest.cs b/src/SkyApm.Abstractions/Transport/LoggerRequest.cs index e2eb14c1..93ed37e4 100644 --- a/src/SkyApm.Abstractions/Transport/LoggerRequest.cs +++ b/src/SkyApm.Abstractions/Transport/LoggerRequest.cs @@ -1,4 +1,22 @@ -锘縰sing System; +锘/* + * Licensed to the SkyAPM under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The SkyAPM licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +using System; using System.Collections.Generic; using System.Text; diff --git a/src/SkyApm.Core/Transport/AsyncQueueSkyApmLogDispatcher.cs b/src/SkyApm.Core/Transport/AsyncQueueSkyApmLogDispatcher.cs index e9464323..1ac49556 100644 --- a/src/SkyApm.Core/Transport/AsyncQueueSkyApmLogDispatcher.cs +++ b/src/SkyApm.Core/Transport/AsyncQueueSkyApmLogDispatcher.cs @@ -1,4 +1,22 @@ -锘縰sing SkyApm.Config; +锘/* + * Licensed to the SkyAPM under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The SkyAPM licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +using SkyApm.Config; using SkyApm.Logging; using SkyApm.Tracing.Segments; using System.Collections.Concurrent; diff --git a/src/SkyApm.Core/Transport/LoggerContextContextMapper.cs b/src/SkyApm.Core/Transport/LoggerContextContextMapper.cs index 942fae2d..3d55cff9 100644 --- a/src/SkyApm.Core/Transport/LoggerContextContextMapper.cs +++ b/src/SkyApm.Core/Transport/LoggerContextContextMapper.cs @@ -1,4 +1,22 @@ -锘縰sing SkyApm.Tracing.Segments; +锘/* + * Licensed to the SkyAPM under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The SkyAPM licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +using SkyApm.Tracing.Segments; namespace SkyApm.Transport { diff --git a/src/SkyApm.Transport.Grpc/V8/LoggerReporter.cs b/src/SkyApm.Transport.Grpc/V8/LoggerReporter.cs index f075e23f..cf06a555 100644 --- a/src/SkyApm.Transport.Grpc/V8/LoggerReporter.cs +++ b/src/SkyApm.Transport.Grpc/V8/LoggerReporter.cs @@ -1,4 +1,22 @@ -锘縰sing SkyApm.Config; +锘/* + * Licensed to the SkyAPM under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The SkyAPM licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +using SkyApm.Config; using SkyApm.Logging; using SkyWalking.NetworkProtocol.V3; using System; diff --git a/src/SkyApm.Utilities.Logging/SkyApmLogger.cs b/src/SkyApm.Utilities.Logging/SkyApmLogger.cs index 2a3c5aac..432b59bd 100644 --- a/src/SkyApm.Utilities.Logging/SkyApmLogger.cs +++ b/src/SkyApm.Utilities.Logging/SkyApmLogger.cs @@ -1,4 +1,22 @@ -锘縰sing Microsoft.Extensions.DependencyInjection; +锘/* + * Licensed to the SkyAPM under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The SkyAPM licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +using Microsoft.Extensions.DependencyInjection; using SkyApm.Logging; using SkyApm.Tracing; using SkyApm.Tracing.Segments; From 091ea586a195481ea181febd7ad3552c725af09a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B3=BD=E5=A8=81=20=E7=8E=8B?= <1585955375@qq.com> Date: Wed, 27 Apr 2022 21:51:25 +0800 Subject: [PATCH 4/6] feat : add a copyright header to all new files --- .../Config/LogPushSkywalkingConfig.cs | 22 +++++++++++++++---- .../Tracing/Segments/LoggerContext.cs | 20 ++++++++++++++++- src/SkyApm.Core/Service/LogReportService.cs | 20 ++++++++++++++++- 3 files changed, 56 insertions(+), 6 deletions(-) diff --git a/src/SkyApm.Abstractions/Config/LogPushSkywalkingConfig.cs b/src/SkyApm.Abstractions/Config/LogPushSkywalkingConfig.cs index 1ffd2f91..1362e5ec 100644 --- a/src/SkyApm.Abstractions/Config/LogPushSkywalkingConfig.cs +++ b/src/SkyApm.Abstractions/Config/LogPushSkywalkingConfig.cs @@ -1,11 +1,25 @@ -锘縰sing System; -using System.Collections.Generic; -using System.Text; +锘/* + * Licensed to the SkyAPM under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The SkyAPM licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ namespace SkyApm.Config { public class LogPushSkywalkingConfig { - public bool Enable { get; set; } + public bool Enable { get; set; } } } diff --git a/src/SkyApm.Abstractions/Tracing/Segments/LoggerContext.cs b/src/SkyApm.Abstractions/Tracing/Segments/LoggerContext.cs index 972f6500..a4f23575 100644 --- a/src/SkyApm.Abstractions/Tracing/Segments/LoggerContext.cs +++ b/src/SkyApm.Abstractions/Tracing/Segments/LoggerContext.cs @@ -1,4 +1,22 @@ -锘縰sing System.Collections.Generic; +锘/* + * Licensed to the SkyAPM under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The SkyAPM licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +using System.Collections.Generic; namespace SkyApm.Tracing.Segments { diff --git a/src/SkyApm.Core/Service/LogReportService.cs b/src/SkyApm.Core/Service/LogReportService.cs index cf9110a6..0a27c3d8 100644 --- a/src/SkyApm.Core/Service/LogReportService.cs +++ b/src/SkyApm.Core/Service/LogReportService.cs @@ -1,4 +1,22 @@ -锘縰sing SkyApm.Config; +锘/* + * Licensed to the SkyAPM under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The SkyAPM licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +using SkyApm.Config; using SkyApm.Logging; using SkyApm.Transport; using System; From 1e68f1e9625d97102542a6c6de6fd4068389ff4b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B3=BD=E5=A8=81=20=E7=8E=8B?= <1585955375@qq.com> Date: Sun, 1 May 2022 20:49:05 +0800 Subject: [PATCH 5/6] feat : Clean up code format --- .../Logging/ILoggerFactory.cs | 2 +- src/SkyApm.Core/Logging/NullLoggerFactory.cs | 2 +- src/SkyApm.Core/SkyApm.Core.csproj | 6 +-- .../Tracing/SegmentContextFactory.cs | 1 + .../V8/SegmentReporter.cs | 38 ------------------- 5 files changed, 4 insertions(+), 45 deletions(-) diff --git a/src/SkyApm.Abstractions/Logging/ILoggerFactory.cs b/src/SkyApm.Abstractions/Logging/ILoggerFactory.cs index e16d01a2..886f0264 100644 --- a/src/SkyApm.Abstractions/Logging/ILoggerFactory.cs +++ b/src/SkyApm.Abstractions/Logging/ILoggerFactory.cs @@ -23,6 +23,6 @@ namespace SkyApm.Logging public interface ILoggerFactory { ILogger CreateLogger(Type type); - SkyApm.Logging.ILogger CreateSkyApmLogger(Type type); + ILogger CreateSkyApmLogger(Type type); } } \ No newline at end of file diff --git a/src/SkyApm.Core/Logging/NullLoggerFactory.cs b/src/SkyApm.Core/Logging/NullLoggerFactory.cs index 4d38934e..32f12805 100644 --- a/src/SkyApm.Core/Logging/NullLoggerFactory.cs +++ b/src/SkyApm.Core/Logging/NullLoggerFactory.cs @@ -29,7 +29,7 @@ public ILogger CreateLogger(Type type) public ILogger CreateSkyApmLogger(Type type) { - throw new NotImplementedException(); + return new NullLogger(); } } } \ No newline at end of file diff --git a/src/SkyApm.Core/SkyApm.Core.csproj b/src/SkyApm.Core/SkyApm.Core.csproj index 2ca89fc1..c1eac56b 100644 --- a/src/SkyApm.Core/SkyApm.Core.csproj +++ b/src/SkyApm.Core/SkyApm.Core.csproj @@ -12,11 +12,7 @@ netstandard2.0 $(DefineConstants);SPAN - + diff --git a/src/SkyApm.Core/Tracing/SegmentContextFactory.cs b/src/SkyApm.Core/Tracing/SegmentContextFactory.cs index 45185e1e..0d9737fb 100644 --- a/src/SkyApm.Core/Tracing/SegmentContextFactory.cs +++ b/src/SkyApm.Core/Tracing/SegmentContextFactory.cs @@ -79,6 +79,7 @@ public SegmentContext CreateEntrySegment(string operationName, ICarrier carrier, segmentContext.References.Add(segmentReference); } _entrySegmentContextAccessor.Context = segmentContext; + return segmentContext; } diff --git a/src/SkyApm.Transport.Grpc/V8/SegmentReporter.cs b/src/SkyApm.Transport.Grpc/V8/SegmentReporter.cs index 74e4ae95..b71b8b86 100644 --- a/src/SkyApm.Transport.Grpc/V8/SegmentReporter.cs +++ b/src/SkyApm.Transport.Grpc/V8/SegmentReporter.cs @@ -64,44 +64,6 @@ public async Task ReportAsync(IReadOnlyCollection segmentRequest await asyncClientStreamingCall.RequestStream.CompleteAsync(); await asyncClientStreamingCall.ResponseAsync; } - - - //var client1 = new LogReportService.LogReportServiceClient(connection); - //using (var asyncClientStreamingCall = client1.collect(_config.GetMeta(), _config.GetReportTimeout(), cancellationToken)) - //{ - // foreach (var item in segmentRequests) - // { - // var logbody = new LogData() - // { - // TraceContext=new TraceContext() - // { - // TraceId=item.TraceId, - // TraceSegmentId=item.Segment.SegmentId, - // //SpanId=item.Segment - // }, - // Timestamp = DateTimeOffset.UtcNow.Ticks, - // Service = item.Segment.ServiceId, - // ServiceInstance = item.Segment.ServiceInstanceId, - // Endpoint = "", - // Body = new LogDataBody() - // { - // Type = "json", - // Json = new JSONLog() - // { - // Json = "测试日志", - // }, - // }, - // }; - // await asyncClientStreamingCall.RequestStream.WriteAsync(logbody); - // } - - // await asyncClientStreamingCall.RequestStream.CompleteAsync(); - // await asyncClientStreamingCall.ResponseAsync; - //} - - - - stopwatch.Stop(); _logger.Information($"Report {segmentRequests.Count} trace segment. cost: {stopwatch.Elapsed}s"); } From 27c72ef4c0f13d25b7e5ef19b5a2d99be1d2adc1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B3=BD=E5=A8=81=20=E7=8E=8B?= <1585955375@qq.com> Date: Wed, 4 May 2022 10:30:56 +0800 Subject: [PATCH 6/6] feat : Modify log docking, separate the docking log item. --- .../Controllers/WeatherForecastController.cs | 9 ++- sample/Sky.Apm.Sample.Logging/Program.cs | 2 +- .../Sky.Apm.Sample.Logging.csproj | 1 + skyapm-dotnet.sln | 9 ++- .../Logging/ILoggerFactory.cs | 1 - .../Extensions/ServiceCollectionExtensions.cs | 16 +--- src/SkyApm.Core/Logging/NullLoggerFactory.cs | 5 -- .../ISkyApmLogger.cs | 11 +++ .../ServiceCollectionExtensions.cs | 28 +++++++ .../SkyApm.Diagnostics.Logging.csproj | 16 ++++ .../SkyApmLogger.cs | 80 +++++++++++++++++++ .../DefaultLoggerFactory.cs | 13 +-- .../SkyApm.Utilities.Logging.csproj | 3 + 13 files changed, 156 insertions(+), 38 deletions(-) create mode 100644 src/SkyApm.Diagnostics.Logging/ISkyApmLogger.cs create mode 100644 src/SkyApm.Diagnostics.Logging/ServiceCollectionExtensions.cs create mode 100644 src/SkyApm.Diagnostics.Logging/SkyApm.Diagnostics.Logging.csproj create mode 100644 src/SkyApm.Diagnostics.Logging/SkyApmLogger.cs diff --git a/sample/Sky.Apm.Sample.Logging/Controllers/WeatherForecastController.cs b/sample/Sky.Apm.Sample.Logging/Controllers/WeatherForecastController.cs index c3e86912..7db6ab19 100644 --- a/sample/Sky.Apm.Sample.Logging/Controllers/WeatherForecastController.cs +++ b/sample/Sky.Apm.Sample.Logging/Controllers/WeatherForecastController.cs @@ -17,6 +17,7 @@ */ using Microsoft.AspNetCore.Mvc; +using SkyApm.Diagnostics.Logging; using SkyApm.Tracing; namespace Sky.Apm.Sample.Logging.Controllers @@ -31,10 +32,10 @@ public class WeatherForecastController : ControllerBase }; private readonly Test _test; - private readonly SkyApm.Logging.ILogger _loggerFactory; - public WeatherForecastController(SkyApm.Logging.ILoggerFactory loggerFactory, Test test) + private readonly ISkyApmLogger _skyApmLogger; + public WeatherForecastController(ISkyApmLogger skyApmLogger, Test test) { - _loggerFactory = loggerFactory.CreateSkyApmLogger(GetType()); + _skyApmLogger = skyApmLogger; _test = test; } @@ -42,7 +43,7 @@ public WeatherForecastController(SkyApm.Logging.ILoggerFactory loggerFactory, Te public IEnumerable Get() { //Console.WriteLine(_entrySegmentContextAccessor.Context?.TraceId); - _loggerFactory.Information("qiwnkasdnaskndlaknd laksndk asndkas ndl nsald nlasdn la锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷"); + _skyApmLogger.Information("涓嬭鍗曟垚鍔燂紒"); _test.Create(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { diff --git a/sample/Sky.Apm.Sample.Logging/Program.cs b/sample/Sky.Apm.Sample.Logging/Program.cs index 7e5d4b78..b1dd1d28 100644 --- a/sample/Sky.Apm.Sample.Logging/Program.cs +++ b/sample/Sky.Apm.Sample.Logging/Program.cs @@ -26,7 +26,7 @@ builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.AddScoped(); -builder.Services.AddPushSkyApmLogger(x => x.Enable = false); +builder.Services.AddPushSkyApmLogger(x => x.Enable = true); var app = builder.Build(); // Configure the HTTP request pipeline. diff --git a/sample/Sky.Apm.Sample.Logging/Sky.Apm.Sample.Logging.csproj b/sample/Sky.Apm.Sample.Logging/Sky.Apm.Sample.Logging.csproj index 819f0ffd..92196e0c 100644 --- a/sample/Sky.Apm.Sample.Logging/Sky.Apm.Sample.Logging.csproj +++ b/sample/Sky.Apm.Sample.Logging/Sky.Apm.Sample.Logging.csproj @@ -19,6 +19,7 @@ + diff --git a/skyapm-dotnet.sln b/skyapm-dotnet.sln index b73c4e9e..e0d49b9f 100644 --- a/skyapm-dotnet.sln +++ b/skyapm-dotnet.sln @@ -109,7 +109,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SkyApm.Diagnostics.FreeSql" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SkyApm.Sample.FreeSqlSqlite", "sample\SkyApm.Sample.FreeSql\SkyApm.Sample.FreeSqlSqlite.csproj", "{B1EF3295-4BF0-489F-8063-C9E3DAE20AA9}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sky.Apm.Sample.Logging", "sample\Sky.Apm.Sample.Logging\Sky.Apm.Sample.Logging.csproj", "{D35905EC-EB46-4A3D-BD2B-02C4C868BC65}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Sky.Apm.Sample.Logging", "sample\Sky.Apm.Sample.Logging\Sky.Apm.Sample.Logging.csproj", "{D35905EC-EB46-4A3D-BD2B-02C4C868BC65}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SkyApm.Diagnostics.Logging", "src\SkyApm.Diagnostics.Logging\SkyApm.Diagnostics.Logging.csproj", "{DDF18F43-E1D2-4854-AC97-DFC321EF6563}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -249,6 +251,10 @@ Global {D35905EC-EB46-4A3D-BD2B-02C4C868BC65}.Debug|Any CPU.Build.0 = Debug|Any CPU {D35905EC-EB46-4A3D-BD2B-02C4C868BC65}.Release|Any CPU.ActiveCfg = Release|Any CPU {D35905EC-EB46-4A3D-BD2B-02C4C868BC65}.Release|Any CPU.Build.0 = Release|Any CPU + {DDF18F43-E1D2-4854-AC97-DFC321EF6563}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DDF18F43-E1D2-4854-AC97-DFC321EF6563}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DDF18F43-E1D2-4854-AC97-DFC321EF6563}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DDF18F43-E1D2-4854-AC97-DFC321EF6563}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -296,6 +302,7 @@ Global {82580A47-9DBC-43E8-B581-0C35147B4FAD} = {B5E677CF-2920-4B0A-A056-E73F6B2CF2BC} {B1EF3295-4BF0-489F-8063-C9E3DAE20AA9} = {844CEACD-4C85-4B15-9E2B-892B01FDA4BB} {D35905EC-EB46-4A3D-BD2B-02C4C868BC65} = {844CEACD-4C85-4B15-9E2B-892B01FDA4BB} + {DDF18F43-E1D2-4854-AC97-DFC321EF6563} = {B5E677CF-2920-4B0A-A056-E73F6B2CF2BC} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {94C0DA2C-CCCB-4314-93A2-9809B5DD0583} diff --git a/src/SkyApm.Abstractions/Logging/ILoggerFactory.cs b/src/SkyApm.Abstractions/Logging/ILoggerFactory.cs index 886f0264..aee68fbc 100644 --- a/src/SkyApm.Abstractions/Logging/ILoggerFactory.cs +++ b/src/SkyApm.Abstractions/Logging/ILoggerFactory.cs @@ -23,6 +23,5 @@ namespace SkyApm.Logging public interface ILoggerFactory { ILogger CreateLogger(Type type); - ILogger CreateSkyApmLogger(Type type); } } \ No newline at end of file diff --git a/src/SkyApm.Agent.Hosting/Extensions/ServiceCollectionExtensions.cs b/src/SkyApm.Agent.Hosting/Extensions/ServiceCollectionExtensions.cs index 21f366db..9d41f14e 100644 --- a/src/SkyApm.Agent.Hosting/Extensions/ServiceCollectionExtensions.cs +++ b/src/SkyApm.Agent.Hosting/Extensions/ServiceCollectionExtensions.cs @@ -47,21 +47,7 @@ public static IServiceCollection AddSkyAPM(this IServiceCollection services, Act return services; } - public static IServiceCollection AddPushSkyApmLogger(this IServiceCollection services,Action action) - { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - if (action == null) - { - throw new ArgumentNullException(nameof(action)); - } - LogPushSkywalkingConfig logPushSkywalking=new LogPushSkywalkingConfig(); - action.Invoke(logPushSkywalking); - services.Configure(action); - return services; - } + internal static IServiceCollection AddSkyAPMCore(this IServiceCollection services, Action extensionsSetup = null) { diff --git a/src/SkyApm.Core/Logging/NullLoggerFactory.cs b/src/SkyApm.Core/Logging/NullLoggerFactory.cs index 32f12805..7320003f 100644 --- a/src/SkyApm.Core/Logging/NullLoggerFactory.cs +++ b/src/SkyApm.Core/Logging/NullLoggerFactory.cs @@ -26,10 +26,5 @@ public ILogger CreateLogger(Type type) { return new NullLogger(); } - - public ILogger CreateSkyApmLogger(Type type) - { - return new NullLogger(); - } } } \ No newline at end of file diff --git a/src/SkyApm.Diagnostics.Logging/ISkyApmLogger.cs b/src/SkyApm.Diagnostics.Logging/ISkyApmLogger.cs new file mode 100644 index 00000000..e429eb5c --- /dev/null +++ b/src/SkyApm.Diagnostics.Logging/ISkyApmLogger.cs @@ -0,0 +1,11 @@ +锘縰sing SkyApm.Logging; + +namespace SkyApm.Diagnostics.Logging +{ + public interface ISkyApmLogger :ILogger + { + + + + } +} \ No newline at end of file diff --git a/src/SkyApm.Diagnostics.Logging/ServiceCollectionExtensions.cs b/src/SkyApm.Diagnostics.Logging/ServiceCollectionExtensions.cs new file mode 100644 index 00000000..097bec0f --- /dev/null +++ b/src/SkyApm.Diagnostics.Logging/ServiceCollectionExtensions.cs @@ -0,0 +1,28 @@ +锘縰sing SkyApm.Config; +using SkyApm.Diagnostics.Logging; +using System; + +namespace Microsoft.Extensions.DependencyInjection +{ + public static class ServiceCollectionExtensions + { + + public static IServiceCollection AddPushSkyApmLogger(this IServiceCollection services, Action action) + { + if (services == null) + { + throw new ArgumentNullException(nameof(services)); + } + if (action == null) + { + throw new ArgumentNullException(nameof(action)); + } + LogPushSkywalkingConfig logPushSkywalking = new LogPushSkywalkingConfig(); + action.Invoke(logPushSkywalking); + services.Configure(action); + + services.Add(new ServiceDescriptor(typeof(ISkyApmLogger<>), typeof(SkyApmLogger<>), ServiceLifetime.Singleton)); + return services; + } + } +} diff --git a/src/SkyApm.Diagnostics.Logging/SkyApm.Diagnostics.Logging.csproj b/src/SkyApm.Diagnostics.Logging/SkyApm.Diagnostics.Logging.csproj new file mode 100644 index 00000000..b9323cf0 --- /dev/null +++ b/src/SkyApm.Diagnostics.Logging/SkyApm.Diagnostics.Logging.csproj @@ -0,0 +1,16 @@ + + + + netcoreapp3.1;net5.0;net6.0 + enable + + + + + + + + + + + diff --git a/src/SkyApm.Diagnostics.Logging/SkyApmLogger.cs b/src/SkyApm.Diagnostics.Logging/SkyApmLogger.cs new file mode 100644 index 00000000..b65cc8b6 --- /dev/null +++ b/src/SkyApm.Diagnostics.Logging/SkyApmLogger.cs @@ -0,0 +1,80 @@ +锘縰sing Microsoft.Extensions.Options; +using SkyApm.Config; +using SkyApm.Logging; +using SkyApm.Tracing; +using SkyApm.Tracing.Segments; +using SkyApm.Transport; +using System; +using System.Collections.Generic; + +namespace SkyApm.Diagnostics.Logging +{ + + public class SkyApmLogger : ISkyApmLogger + { + + private readonly bool _pushSkywalking; + private readonly Type _loggerName; + private readonly IEntrySegmentContextAccessor _entrySegmentContextAccessor; + private readonly ISkyApmLogDispatcher _skyApmLogDispatcher; + public SkyApmLogger(IEntrySegmentContextAccessor entrySegmentContextAccessor, ISkyApmLogDispatcher skyApmLogDispatcher, IOptions logPushSkywalkingConfig) + { + _loggerName = typeof(TCategoryName); + _entrySegmentContextAccessor = entrySegmentContextAccessor; + _skyApmLogDispatcher = skyApmLogDispatcher; + _pushSkywalking = logPushSkywalkingConfig.Value.Enable; + } + + public void Debug(string message) + { + SendLog("Debug", message); + } + + public void Error(string message, Exception exception) + { + SendLog("Error", message); + } + + public void Information(string message) + { + SendLog("Information", message); + } + + public void Trace(string message) + { + SendLog("Trace", message); + } + + public void Warning(string message) + { + SendLog("Warning", message); + } + + private void SendLog(string logLevel, string message) + { + if (_pushSkywalking) + { + var logs = new Dictionary(); + logs.Add("className", _loggerName); + logs.Add("Level", logLevel); + logs.Add("logMessage", message); + var logContext = new LoggerContext() + { + Logs = logs, + SegmentContext = _entrySegmentContextAccessor.Context, + }; + _skyApmLogDispatcher.Dispatch(logContext); + } + + } + + } + + //public class SkyApmLoggerFactory : ILoggerFactory + //{ + // public ILogger CreateLogger(Type type) + // { + // throw new NotImplementedException(); + // } + //} +} \ No newline at end of file diff --git a/src/SkyApm.Utilities.Logging/DefaultLoggerFactory.cs b/src/SkyApm.Utilities.Logging/DefaultLoggerFactory.cs index 20331e4e..e2f3e827 100644 --- a/src/SkyApm.Utilities.Logging/DefaultLoggerFactory.cs +++ b/src/SkyApm.Utilities.Logging/DefaultLoggerFactory.cs @@ -24,7 +24,6 @@ using ILogger = SkyApm.Logging.ILogger; using ILoggerFactory = SkyApm.Logging.ILoggerFactory; using MSLoggerFactory = Microsoft.Extensions.Logging.LoggerFactory; -using Microsoft.Extensions.Options; namespace SkyApm.Utilities.Logging { @@ -35,13 +34,10 @@ public class DefaultLoggerFactory : SkyApm.Logging.ILoggerFactory private readonly MSLoggerFactory _loggerFactory; private readonly LoggingConfig _loggingConfig; - private readonly IServiceProvider _serviceProvider; - private readonly IOptions _logPushSkywalkingConfig; - public DefaultLoggerFactory(IConfigAccessor configAccessor, IServiceProvider serviceProvider, IOptions logPushSkywalkingConfig) + + public DefaultLoggerFactory(IConfigAccessor configAccessor) { - _serviceProvider= serviceProvider; _loggingConfig = configAccessor.Get(); - _logPushSkywalkingConfig = logPushSkywalkingConfig; _loggerFactory = new MSLoggerFactory(); var instrumentationConfig = configAccessor.Get(); @@ -60,11 +56,6 @@ public SkyApm.Logging.ILogger CreateLogger(Type type) return new DefaultLogger(_loggerFactory.CreateLogger(type)); } - public SkyApm.Logging.ILogger CreateSkyApmLogger(Type type) - { - return new SkyApmLogger(type, _serviceProvider, _logPushSkywalkingConfig.Value.Enable); - } - private static LogEventLevel EventLevel(string level) { return LogEventLevel.TryParse(level, out var logEventLevel) diff --git a/src/SkyApm.Utilities.Logging/SkyApm.Utilities.Logging.csproj b/src/SkyApm.Utilities.Logging/SkyApm.Utilities.Logging.csproj index eddb8c2b..f7ba76df 100644 --- a/src/SkyApm.Utilities.Logging/SkyApm.Utilities.Logging.csproj +++ b/src/SkyApm.Utilities.Logging/SkyApm.Utilities.Logging.csproj @@ -12,6 +12,9 @@ SkyApm.Utilities.Logging + + +