From ac4529199d4fc22ef5ac3e81152b88b5cc3fbeff Mon Sep 17 00:00:00 2001 From: yao Date: Thu, 7 Nov 2024 23:28:30 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8A=A0=E5=85=A5=E5=B0=88=E6=A1=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- StructLog/Lab.Loki/.dockerignore | 25 +++++ StructLog/Lab.Loki/Lab.Loki.WebApi/Dockerfile | 23 +++++ .../Lab.Loki.WebApi/Lab.Loki.WebApi.csproj | 20 ++++ .../Lab.Loki.WebApi/Lab.Loki.WebApi.http | 6 ++ .../Lab.Loki.WebApi/MemberController.cs | 20 ++++ StructLog/Lab.Loki/Lab.Loki.WebApi/Program.cs | 93 +++++++++++++++++++ .../Properties/launchSettings.json | 41 ++++++++ .../appsettings.Development.json | 8 ++ .../Lab.Loki/Lab.Loki.WebApi/appsettings.json | 9 ++ StructLog/Lab.Loki/Lab.Loki.sln | 16 ++++ StructLog/Lab.Loki/docker-compose.yaml | 57 ++++++++++++ StructLog/Lab.Loki/loki-config.yaml | 50 ++++++++++ StructLog/Lab.Loki/promtail-config.yaml | 18 ++++ 13 files changed, 386 insertions(+) create mode 100644 StructLog/Lab.Loki/.dockerignore create mode 100644 StructLog/Lab.Loki/Lab.Loki.WebApi/Dockerfile create mode 100644 StructLog/Lab.Loki/Lab.Loki.WebApi/Lab.Loki.WebApi.csproj create mode 100644 StructLog/Lab.Loki/Lab.Loki.WebApi/Lab.Loki.WebApi.http create mode 100644 StructLog/Lab.Loki/Lab.Loki.WebApi/MemberController.cs create mode 100644 StructLog/Lab.Loki/Lab.Loki.WebApi/Program.cs create mode 100644 StructLog/Lab.Loki/Lab.Loki.WebApi/Properties/launchSettings.json create mode 100644 StructLog/Lab.Loki/Lab.Loki.WebApi/appsettings.Development.json create mode 100644 StructLog/Lab.Loki/Lab.Loki.WebApi/appsettings.json create mode 100644 StructLog/Lab.Loki/Lab.Loki.sln create mode 100644 StructLog/Lab.Loki/docker-compose.yaml create mode 100644 StructLog/Lab.Loki/loki-config.yaml create mode 100644 StructLog/Lab.Loki/promtail-config.yaml diff --git a/StructLog/Lab.Loki/.dockerignore b/StructLog/Lab.Loki/.dockerignore new file mode 100644 index 00000000..cd967fc3 --- /dev/null +++ b/StructLog/Lab.Loki/.dockerignore @@ -0,0 +1,25 @@ +**/.dockerignore +**/.env +**/.git +**/.gitignore +**/.project +**/.settings +**/.toolstarget +**/.vs +**/.vscode +**/.idea +**/*.*proj.user +**/*.dbmdl +**/*.jfm +**/azds.yaml +**/bin +**/charts +**/docker-compose* +**/Dockerfile* +**/node_modules +**/npm-debug.log +**/obj +**/secrets.dev.yaml +**/values.dev.yaml +LICENSE +README.md \ No newline at end of file diff --git a/StructLog/Lab.Loki/Lab.Loki.WebApi/Dockerfile b/StructLog/Lab.Loki/Lab.Loki.WebApi/Dockerfile new file mode 100644 index 00000000..a12cedde --- /dev/null +++ b/StructLog/Lab.Loki/Lab.Loki.WebApi/Dockerfile @@ -0,0 +1,23 @@ +FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base +USER $APP_UID +WORKDIR /app +EXPOSE 8080 +EXPOSE 8081 + +FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build +ARG BUILD_CONFIGURATION=Release +WORKDIR /src +COPY ["Lab.Loki.WebApi/Lab.Loki.WebApi.csproj", "Lab.Loki.WebApi/"] +RUN dotnet restore "Lab.Loki.WebApi/Lab.Loki.WebApi.csproj" +COPY . . +WORKDIR "/src/Lab.Loki.WebApi" +RUN dotnet build "Lab.Loki.WebApi.csproj" -c $BUILD_CONFIGURATION -o /app/build + +FROM build AS publish +ARG BUILD_CONFIGURATION=Release +RUN dotnet publish "Lab.Loki.WebApi.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false + +FROM base AS final +WORKDIR /app +COPY --from=publish /app/publish . +ENTRYPOINT ["dotnet", "Lab.Loki.WebApi.dll"] diff --git a/StructLog/Lab.Loki/Lab.Loki.WebApi/Lab.Loki.WebApi.csproj b/StructLog/Lab.Loki/Lab.Loki.WebApi/Lab.Loki.WebApi.csproj new file mode 100644 index 00000000..edf08e62 --- /dev/null +++ b/StructLog/Lab.Loki/Lab.Loki.WebApi/Lab.Loki.WebApi.csproj @@ -0,0 +1,20 @@ + + + + net8.0 + enable + enable + Linux + + + + + + + + + + + + + diff --git a/StructLog/Lab.Loki/Lab.Loki.WebApi/Lab.Loki.WebApi.http b/StructLog/Lab.Loki/Lab.Loki.WebApi/Lab.Loki.WebApi.http new file mode 100644 index 00000000..84b45c41 --- /dev/null +++ b/StructLog/Lab.Loki/Lab.Loki.WebApi/Lab.Loki.WebApi.http @@ -0,0 +1,6 @@ +@Lab.Loki.WebApi_HostAddress = http://localhost:5050 + +GET {{Lab.Loki.WebApi_HostAddress}}/weatherforecast/ +Accept: application/json + +### diff --git a/StructLog/Lab.Loki/Lab.Loki.WebApi/MemberController.cs b/StructLog/Lab.Loki/Lab.Loki.WebApi/MemberController.cs new file mode 100644 index 00000000..69e366ce --- /dev/null +++ b/StructLog/Lab.Loki/Lab.Loki.WebApi/MemberController.cs @@ -0,0 +1,20 @@ +using Microsoft.AspNetCore.Mvc; + +namespace Lab.Loki.WebApi; + +[ApiController] +public class MemberV1Controller(ILogger Logger) : ControllerBase +{ + [HttpGet] + [Route("api/v1/members", Name = "GetMember")] + public async Task GetMemberCursor( + CancellationToken cancel = default) + { + Logger.LogInformation(new EventId(2000, "Trace"), "Start {ControllerName}.{MethodName}...", + nameof(MemberV1Controller), nameof(GetMemberCursor)); + + var sensorInput = new { Latitude = 25, Longitude = 134 }; + Logger.LogInformation("Processing {@SensorInput}", sensorInput); + return this.Ok(); + } +} \ No newline at end of file diff --git a/StructLog/Lab.Loki/Lab.Loki.WebApi/Program.cs b/StructLog/Lab.Loki/Lab.Loki.WebApi/Program.cs new file mode 100644 index 00000000..f3a8b105 --- /dev/null +++ b/StructLog/Lab.Loki/Lab.Loki.WebApi/Program.cs @@ -0,0 +1,93 @@ +using Serilog; +using Serilog.Events; +using Serilog.Sinks.Grafana.Loki; + +Log.Logger = new LoggerConfiguration() + .MinimumLevel.Information() + .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning) + .Enrich.FromLogContext() + .WriteTo.Console() + .WriteTo.File("logs/host-.txt", rollingInterval: RollingInterval.Hour) + .WriteTo.Seq("http://localhost:5341") + .WriteTo.GrafanaLoki("http://localhost:3100") + .CreateLogger(); +Log.Information("Starting web host"); + +try +{ + var builder = WebApplication.CreateBuilder(args); + + // Add services to the container. + builder.Services.AddControllers() + ; + builder.Host + .UseSerilog((context, services, config) => + config.ReadFrom.Configuration(context.Configuration) + .ReadFrom.Services(services) + .Enrich.FromLogContext() + .WriteTo.Console() //正式環境不要用 Console,除非有 Log Provider 專門用來收集 Console Log + .WriteTo.Seq("http://localhost:5341") //log server + .WriteTo.File("logs/aspnet-.txt", rollingInterval: RollingInterval.Minute) //正式環境不要用 File + ); + + // 確定物件都有設定 DI Container + builder.Host.UseDefaultServiceProvider(p => + { + p.ValidateScopes = true; + p.ValidateOnBuild = true; + }); + var configuration = builder.Configuration; + + // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle + builder.Services.AddEndpointsApiExplorer(); + builder.Services.AddSwaggerGen(); + builder.Services.AddHttpContextAccessor(); + + builder.Services.AddSingleton(_ => TimeProvider.System); + var app = builder.Build(); + + // Configure the HTTP request pipeline. + if (app.Environment.IsDevelopment()) + { + app.UseSwagger(); + app.UseSwaggerUI(options => + options.SwaggerEndpoint("/swagger/v1/swagger.yaml", + "Swagger Demo Documentation v1")); + } + + app.UseAuthorization(); + app.MapDefaultControllerRoute(); + app.UseRouting(); + app.UseEndpoints(endpoints => + { + //注册Web API Controller + endpoints.MapControllers(); + + //注册MVC Controller模板 {controller=Home}/{action=Index}/{id?} + // endpoints.MapDefaultControllerRoute(); + + //注册健康检查 + // endpoints.MapHealthChecks("/_hc"); + }); + app.UseSerilogRequestLogging(); + app.UseHttpsRedirection(); + app.MapControllers(); + app.Run(); + return 0; +} +catch (Exception ex) +{ + Log.Fatal(ex, "Host terminated unexpectedly"); + return 1; +} +finally +{ + Log.CloseAndFlush(); +} + +namespace JobBank1111.Job.WebAPI +{ + public partial class Program + { + } +} \ No newline at end of file diff --git a/StructLog/Lab.Loki/Lab.Loki.WebApi/Properties/launchSettings.json b/StructLog/Lab.Loki/Lab.Loki.WebApi/Properties/launchSettings.json new file mode 100644 index 00000000..16e84809 --- /dev/null +++ b/StructLog/Lab.Loki/Lab.Loki.WebApi/Properties/launchSettings.json @@ -0,0 +1,41 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:17826", + "sslPort": 44397 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "http://localhost:5050", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "https://localhost:7276;http://localhost:5050", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/StructLog/Lab.Loki/Lab.Loki.WebApi/appsettings.Development.json b/StructLog/Lab.Loki/Lab.Loki.WebApi/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/StructLog/Lab.Loki/Lab.Loki.WebApi/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/StructLog/Lab.Loki/Lab.Loki.WebApi/appsettings.json b/StructLog/Lab.Loki/Lab.Loki.WebApi/appsettings.json new file mode 100644 index 00000000..10f68b8c --- /dev/null +++ b/StructLog/Lab.Loki/Lab.Loki.WebApi/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/StructLog/Lab.Loki/Lab.Loki.sln b/StructLog/Lab.Loki/Lab.Loki.sln new file mode 100644 index 00000000..c1b3162f --- /dev/null +++ b/StructLog/Lab.Loki/Lab.Loki.sln @@ -0,0 +1,16 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lab.Loki.WebApi", "Lab.Loki.WebApi\Lab.Loki.WebApi.csproj", "{D18685EA-F933-464C-801D-6B92EA3B7DA5}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {D18685EA-F933-464C-801D-6B92EA3B7DA5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D18685EA-F933-464C-801D-6B92EA3B7DA5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D18685EA-F933-464C-801D-6B92EA3B7DA5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D18685EA-F933-464C-801D-6B92EA3B7DA5}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal diff --git a/StructLog/Lab.Loki/docker-compose.yaml b/StructLog/Lab.Loki/docker-compose.yaml new file mode 100644 index 00000000..8ca3d52c --- /dev/null +++ b/StructLog/Lab.Loki/docker-compose.yaml @@ -0,0 +1,57 @@ +version: "3" + +networks: + loki: + +services: + seq: + image: datalust/seq:latest + ports: + - "5341:80" + environment: + - ACCEPT_EULA=Y + loki: + image: grafana/loki:2.9.2 + ports: + - "3100:3100" + command: -config.file=/etc/loki/local-config.yaml + networks: + - loki + + promtail: + image: grafana/promtail:2.9.2 + volumes: + - /var/log:/var/log + command: -config.file=/etc/promtail/config.yml + networks: + - loki + + grafana: + environment: + - GF_PATHS_PROVISIONING=/etc/grafana/provisioning + - GF_AUTH_ANONYMOUS_ENABLED=true + - GF_AUTH_ANONYMOUS_ORG_ROLE=Admin + entrypoint: + - sh + - -euc + - | + mkdir -p /etc/grafana/provisioning/datasources + cat < /etc/grafana/provisioning/datasources/ds.yaml + apiVersion: 1 + datasources: + - name: Loki + type: loki + access: proxy + orgId: 1 + url: http://loki:3100 + basicAuth: false + isDefault: true + version: 1 + editable: false + EOF + /run.sh + image: grafana/grafana:latest + ports: + - "3000:3000" + networks: + - loki diff --git a/StructLog/Lab.Loki/loki-config.yaml b/StructLog/Lab.Loki/loki-config.yaml new file mode 100644 index 00000000..e448dfd9 --- /dev/null +++ b/StructLog/Lab.Loki/loki-config.yaml @@ -0,0 +1,50 @@ +auth_enabled: false + +server: + http_listen_port: 3100 + grpc_listen_port: 9096 + +common: + instance_addr: 127.0.0.1 + path_prefix: /tmp/loki + storage: + filesystem: + chunks_directory: /tmp/loki/chunks + rules_directory: /tmp/loki/rules + replication_factor: 1 + ring: + kvstore: + store: inmemory + +query_range: + results_cache: + cache: + embedded_cache: + enabled: true + max_size_mb: 100 + +schema_config: + configs: + - from: 2020-10-24 + store: tsdb + object_store: filesystem + schema: v13 + index: + prefix: index_ + period: 24h + +ruler: + alertmanager_url: http://localhost:9093 + +# By default, Loki will send anonymous, but uniquely-identifiable usage and configuration +# analytics to Grafana Labs. These statistics are sent to https://stats.grafana.org/ +# +# Statistics help us better understand how Loki is used, and they show us performance +# levels for most users. This helps us prioritize features and documentation. +# For more information on what's sent, look at +# https://github.com/grafana/loki/blob/main/pkg/analytics/stats.go +# Refer to the buildReport method to see what goes into a report. +# +# If you would like to disable reporting, uncomment the following lines: +#analytics: +# reporting_enabled: false diff --git a/StructLog/Lab.Loki/promtail-config.yaml b/StructLog/Lab.Loki/promtail-config.yaml new file mode 100644 index 00000000..ed06e8cd --- /dev/null +++ b/StructLog/Lab.Loki/promtail-config.yaml @@ -0,0 +1,18 @@ +server: + http_listen_port: 9080 + grpc_listen_port: 0 + +positions: + filename: /tmp/positions.yaml + +clients: + - url: http://loki:3100/loki/api/v1/push + +scrape_configs: +- job_name: system + static_configs: + - targets: + - localhost + labels: + job: varlogs + __path__: /var/log/*log