Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(deps): Serilog for logging #221

Merged
merged 1 commit into from
May 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions CorpusSearch/Controllers/StatisticsController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Linq;
using CorpusSearch.Service;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace CorpusSearch.Controllers;

Expand Down Expand Up @@ -32,7 +33,8 @@ public FileResult ManxTermFrequency([FromRoute] string language)
}

public static void Init((long totalDocuments, long totalManxTerms) databaseCount,
List<(string, long)> termFrequency)
List<(string, long)> termFrequency,
ILogger<Startup> logger)
{
_documentCount = databaseCount.totalDocuments;
_manxWordCount = databaseCount.totalManxTerms;
Expand All @@ -41,7 +43,7 @@ public static void Init((long totalDocuments, long totalManxTerms) databaseCount
Term = x.Item1,
Frequency = x.Item2
}).OrderByDescending(x => x.Frequency).ToList();
Console.WriteLine($"{databaseCount.totalManxTerms} in {databaseCount.totalDocuments} documents");
logger.LogInformation("{TotalManxTerms} in {TotalDocuments} documents", databaseCount.totalManxTerms, databaseCount.totalDocuments);
}

record TermFrequency
Expand Down
4 changes: 3 additions & 1 deletion CorpusSearch/CorpusSearch.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,10 @@
<PackageReference Include="Lucene.Net.Analysis.Common" Version="4.8.0-beta00014" />
<PackageReference Include="Microsoft.AspNetCore.SpaServices.Extensions" Version="5.0.2" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.1" />
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
<PackageReference Include="sly" Version="2.6.4.2" />
<PackageReference Include="System.Text.Json" Version="5.0.1" />
<PackageReference Include="System.Text.Json" Version="8.0.3" />
</ItemGroup>

<ItemGroup>
Expand Down
2 changes: 2 additions & 0 deletions CorpusSearch/Program.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Serilog;

namespace CorpusSearch;

Expand All @@ -12,6 +13,7 @@ public static void Main(string[] args)

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSerilog((ctx, lc) => lc.WriteTo.Console().ReadFrom.Configuration(ctx.Configuration))
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
Expand Down
5 changes: 3 additions & 2 deletions CorpusSearch/Service/Dictionaries/CregeenDictionaryService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System.Web;
using CorpusSearch.Model.Dictionary;
using HtmlAgilityPack;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace CorpusSearch.Service.Dictionaries;
Expand Down Expand Up @@ -44,7 +45,7 @@ public class CregeenDictionaryService(ISet<string> allWords, IList<CregeenEntry>
public bool LinkToDictionary => true;
public List<string> QueryLanguages => ["gv"];

public static CregeenDictionaryService Init()
public static CregeenDictionaryService Init(ILogger<CregeenDictionaryService> log)
{
HashSet<string> allWords;

Expand All @@ -58,7 +59,7 @@ public static CregeenDictionaryService Init()
catch (Exception)
{
// TODO: Add to health check
Console.WriteLine("Failed to load Cregeen");
log.LogError("Failed to load Cregeen");
allWords = [];
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.IO;
using System.Linq;
using CorpusSearch.Model.Dictionary;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace CorpusSearch.Service.Dictionaries;
Expand All @@ -16,7 +17,7 @@ public class KellyManxToEnglishDictionaryService(ISet<string> allWords, IList<Ke

public bool LinkToDictionary => false;

public static KellyManxToEnglishDictionaryService Init()
public static KellyManxToEnglishDictionaryService Init(ILogger<KellyManxToEnglishDictionaryService> log)
{
HashSet<string> allWords;

Expand All @@ -30,7 +31,7 @@ public static KellyManxToEnglishDictionaryService Init()
catch (Exception)
{
// TODO: Add to health check
Console.WriteLine("Failed to load Kelly");
log.LogError("Failed to load Kelly");
allWords = [];
}

Expand Down
6 changes: 4 additions & 2 deletions CorpusSearch/Service/RecentDocumentsService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,17 @@
using System.Collections.Generic;
using System.Linq;
using CorpusSearch.Model;
using Microsoft.Extensions.Logging;
using Serilog;

namespace CorpusSearch.Service;

public class RecentDocumentsService
{
private List<RecentDocument> documents = [];
public void Init(List<RecentDocument> latestDocuments)
public void Init(List<RecentDocument> latestDocuments, ILogger<Startup> log)
{
Console.WriteLine("Found {0} latest documents", latestDocuments.Count);
log.LogInformation("Found {Count} latest documents", latestDocuments.Count);
documents = latestDocuments;
}

Expand Down
31 changes: 18 additions & 13 deletions CorpusSearch/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@
using CorpusSearch.Service;
using CorpusSearch.Service.Dictionaries;
using CorpusSearch.Utils;
using Microsoft.Extensions.Logging;
using Serilog;
using static System.Text.Json.JsonSerializer;
using ILogger = Microsoft.Extensions.Logging.ILogger;

namespace CorpusSearch;

Expand All @@ -45,11 +48,11 @@ public class Startup(IConfiguration configuration)

public IConfiguration Configuration { get; } = configuration;

private ILogger<Startup> log;

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{

services.AddControllersWithViews().AddJsonOptions(options =>
{
options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
Expand All @@ -58,9 +61,9 @@ public void ConfigureServices(IServiceCollection services)
services.AddSingleton(provider => LuceneIndex.GetInstance());
services.AddSingleton(provider => SearchParser.GetParser());
services.AddSingleton<Searcher>();
services.AddSingleton(provider => CregeenDictionaryService.Init());
services.AddSingleton(provider => CregeenDictionaryService.Init(provider.GetService<ILogger<CregeenDictionaryService>>()));
services.AddSingleton<ISearchDictionary>(provider => provider.GetService<CregeenDictionaryService>());
services.AddSingleton(provider => KellyManxToEnglishDictionaryService.Init());
services.AddSingleton(provider => KellyManxToEnglishDictionaryService.Init(provider.GetService<ILogger<KellyManxToEnglishDictionaryService>>()));
services.AddSingleton<ISearchDictionary>(provider => provider.GetService<KellyManxToEnglishDictionaryService>());
services.AddSingleton<WorkService>();
services.AddSingleton<DocumentSearchService>();
Expand All @@ -79,9 +82,11 @@ public void ConfigureServices(IServiceCollection services)
public void Configure(IApplicationBuilder app,
IWebHostEnvironment env,
WorkService workService,
ILogger<Startup> logger,
Searcher searcher,
RecentDocumentsService recentDocumentsService)
{
log = logger;
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
Expand All @@ -95,23 +100,23 @@ public void Configure(IApplicationBuilder app,

if (!AnonymousAnalytics.Init())
{
Console.WriteLine("Failed to init anonymous analytics. Was CORPUS_SEARCH_SEGMENT_KEY set?");
log.LogWarning("Failed to init anonymous analytics. Was CORPUS_SEARCH_SEGMENT_KEY set?");
}
var lConfig = Configuration.GetSection("Loading").Get<LoadConfig>();

var databaseCount = SetupDatabase(workService, searcher, lConfig);
var termFrequency = searcher.QueryTermFrequency();
StatisticsController.Init(databaseCount, termFrequency);
StatisticsController.Init(databaseCount, termFrequency, log);
SetupDictionaries();

try
{
var latestDocuments = OpenDataLoader.LoadRecentDocuments(workService).Result;
recentDocumentsService.Init(latestDocuments);
recentDocumentsService.Init(latestDocuments, log);
}
catch (Exception e)
{
Console.WriteLine("failed to read latest documents {0}", e);
log.LogError(e , "failed to read latest documents");
}

// app.UseHttpsRedirection();
Expand Down Expand Up @@ -162,38 +167,38 @@ Dictionary<string, IList<string>> ToCaseInsensitiveDict(FileStream fileStream)
}
}

internal static (long totalDocuments, long totalManxTerms) SetupDatabase(WorkService workService, Searcher searcher, LoadConfig lConfig)
internal (long totalDocuments, long totalManxTerms) SetupDatabase(WorkService workService, Searcher searcher, LoadConfig lConfig)
{
var totalDocuments = 0L;

bool ignoreClosedData = lConfig?.OpenDataOnly ?? false;
if (!ignoreClosedData) try
{
List<Document> closedSourceDocument = ClosedDataLoader.LoadDocumentsFromFile().Cast<Document>().ToList();
Console.WriteLine($"Loaded {closedSourceDocument.Count} documents");
log.LogInformation("Loaded {Count} documents", closedSourceDocument.Count);
AddDocuments(closedSourceDocument, workService, searcher);
totalDocuments += closedSourceDocument.Count;
}
catch (Exception e)
{
Console.WriteLine($"Failed loading documents: {e}");
log.LogError(e, "Failed loading documents");
}
// Try adding open source documents
try
{
List<Document> ossDocuments = OpenDataLoader.LoadDocumentsFromFile(lConfig).Cast<Document>().ToList();
Console.WriteLine($"Loaded {ossDocuments.Count} documents");
log.LogInformation("Loaded {OssDocumentsCount} documents", ossDocuments.Count);
AddDocuments(ossDocuments, workService, searcher);
totalDocuments += ossDocuments.Count;
}
catch (Exception e)
{
Console.WriteLine($"Failed loading documents: {e}");
log.LogError(e, "Failed loading documents");
}

var stopWatch = System.Diagnostics.Stopwatch.StartNew();
searcher.OnAllDocumentsAdded();
Console.WriteLine($"compacted in {stopWatch.ElapsedMilliseconds}");
log.LogDebug("compacted in {CompactedInMilliseconds}", stopWatch.ElapsedMilliseconds);

var totalTerms = searcher.CountManxTerms();
return (totalDocuments, totalTerms);
Expand Down
Loading