Skip to content

Commit

Permalink
加入專案
Browse files Browse the repository at this point in the history
  • Loading branch information
yaochangyu committed Nov 7, 2024
1 parent 10bb23b commit ac45291
Show file tree
Hide file tree
Showing 13 changed files with 386 additions and 0 deletions.
25 changes: 25 additions & 0 deletions StructLog/Lab.Loki/.dockerignore
Original file line number Diff line number Diff line change
@@ -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
23 changes: 23 additions & 0 deletions StructLog/Lab.Loki/Lab.Loki.WebApi/Dockerfile
Original file line number Diff line number Diff line change
@@ -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"]
20 changes: 20 additions & 0 deletions StructLog/Lab.Loki/Lab.Loki.WebApi/Lab.Loki.WebApi.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.8"/>
<PackageReference Include="Scalar.AspNetCore" Version="1.2.31" />
<PackageReference Include="Serilog.Sinks.Grafana.Loki" Version="8.3.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0"/>
<PackageReference Include="Serilog.AspNetCore" Version="8.0.3" />
<PackageReference Include="Serilog.Sinks.Seq" Version="8.0.0" />

</ItemGroup>

</Project>
6 changes: 6 additions & 0 deletions StructLog/Lab.Loki/Lab.Loki.WebApi/Lab.Loki.WebApi.http
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
@Lab.Loki.WebApi_HostAddress = http://localhost:5050

GET {{Lab.Loki.WebApi_HostAddress}}/weatherforecast/
Accept: application/json

###
20 changes: 20 additions & 0 deletions StructLog/Lab.Loki/Lab.Loki.WebApi/MemberController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using Microsoft.AspNetCore.Mvc;

namespace Lab.Loki.WebApi;

[ApiController]
public class MemberV1Controller(ILogger<MemberV1Controller> Logger) : ControllerBase
{
[HttpGet]
[Route("api/v1/members", Name = "GetMember")]
public async Task<ActionResult> 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();
}
}
93 changes: 93 additions & 0 deletions StructLog/Lab.Loki/Lab.Loki.WebApi/Program.cs
Original file line number Diff line number Diff line change
@@ -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>(_ => 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
{
}
}
41 changes: 41 additions & 0 deletions StructLog/Lab.Loki/Lab.Loki.WebApi/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -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"
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
9 changes: 9 additions & 0 deletions StructLog/Lab.Loki/Lab.Loki.WebApi/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
16 changes: 16 additions & 0 deletions StructLog/Lab.Loki/Lab.Loki.sln
Original file line number Diff line number Diff line change
@@ -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
57 changes: 57 additions & 0 deletions StructLog/Lab.Loki/docker-compose.yaml
Original file line number Diff line number Diff line change
@@ -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 <<EOF > /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
50 changes: 50 additions & 0 deletions StructLog/Lab.Loki/loki-config.yaml
Original file line number Diff line number Diff line change
@@ -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
Loading

0 comments on commit ac45291

Please sign in to comment.