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

Add loggingpath to settings.json #193

Merged
merged 2 commits into from
Sep 2, 2021
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
31 changes: 31 additions & 0 deletions src/Papercut.Core/Domain/Paths/ILoggingPathConfigurator..cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Papercut
//
// Copyright © 2008 - 2012 Ken Robertson
// Copyright © 2013 - 2020 Jaben Cargman
//
// Licensed 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 Papercut.Core.Domain.Paths
{
using System;
using System.Collections.Generic;

public interface ILoggingPathConfigurator
{
string DefaultSavePath { get; }

IEnumerable<string> LoadPaths { get; }

event EventHandler RefreshLoadPath;
}
}
3 changes: 2 additions & 1 deletion src/Papercut.Core/Domain/Paths/IPathTemplatesProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ namespace Papercut.Core.Domain.Paths

public interface IPathTemplatesProvider
{
ObservableCollection<string> PathTemplates { get; }
ObservableCollection<string> MessagePathTemplates { get; }
ObservableCollection<string> LoggingPathTemplates { get; }
}
}
168 changes: 168 additions & 0 deletions src/Papercut.Core/Domain/Paths/LoggingPathConfigurator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
// Papercut
//
// Copyright © 2008 - 2012 Ken Robertson
// Copyright © 2013 - 2020 Jaben Cargman
//
// Licensed 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 Papercut.Core.Domain.Paths
{
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;

using Common;

using Papercut.Common.Helper;

using Serilog;

public class LoggingPathConfigurator : ILoggingPathConfigurator
{
static readonly IDictionary<string, string> _templateDictionary;

static readonly Regex TemplateRegex = new Regex(
@"\%(?<name>.+?)\%",
RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.Singleline);

readonly ILogger _logger;

readonly IPathTemplatesProvider _pathTemplateProvider;

string _defaultSavePath;

static LoggingPathConfigurator()
{
_templateDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{"BaseDirectory", AppDomain.CurrentDomain.BaseDirectory},
{"DataDirectory", AppConstants.DataDirectory}
};

foreach (
Environment.SpecialFolder specialPath in
EnumHelpers.GetEnumList<Environment.SpecialFolder>())
{
string specialPathName = specialPath.ToString();

if (!_templateDictionary.ContainsKey(specialPathName)) _templateDictionary.Add(specialPathName, Environment.GetFolderPath(specialPath));
}
}

public LoggingPathConfigurator(IPathTemplatesProvider pathTemplateProvider, ILogger logger)
{
if (pathTemplateProvider == null) throw new ArgumentNullException(nameof(pathTemplateProvider));
if (logger == null) throw new ArgumentNullException(nameof(logger));

this._logger = logger;
this._pathTemplateProvider = pathTemplateProvider;
this._pathTemplateProvider.LoggingPathTemplates.CollectionChanged += this.PathTemplatesCollectionChanged;

this.DefaultSavePath = AppDomain.CurrentDomain.BaseDirectory;
this.RenderLoadPaths();

if (this.LoadPaths.Any()) this.DefaultSavePath = this.LoadPaths.First();

this._logger.Information(
"Default Logging Save Path is Set to {DefaultSavePath}",
this.DefaultSavePath);
}

public string DefaultSavePath
{
get
{
if (!Directory.Exists(this._defaultSavePath))
{
this._logger.Information(
"Creating Default Logging Save Path {DefaultSavePath} because it does not exist",
this._defaultSavePath);

Directory.CreateDirectory(this._defaultSavePath);
}

return this._defaultSavePath;
}
private set => this._defaultSavePath = value;
}

public IEnumerable<string> LoadPaths { get; private set; }

public event EventHandler RefreshLoadPath;

void PathTemplatesCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
this.RenderLoadPaths();
this.OnRefreshLoadPath();
}

void RenderLoadPaths()
{
this.LoadPaths =
this._pathTemplateProvider.LoggingPathTemplates.Select(this.RenderPathTemplate)
.Where(this.ValidatePathExists)
.ToList();

this._logger.Information("Saving logs in the Following Path(s) {@LoadPaths}", this.LoadPaths);
}

protected virtual void OnRefreshLoadPath()
{
EventHandler handler = this.RefreshLoadPath;
handler?.Invoke(this, EventArgs.Empty);
}

string RenderPathTemplate(string pathTemplate)
{
IEnumerable<string> pathKeys =
TemplateRegex.Matches(pathTemplate)
.OfType<Match>()
.Select(s => s.Groups["name"].Value);
string renderedPath = pathTemplate;

foreach (string pathKeyName in pathKeys)
{
string path;
if (_templateDictionary.TryGetValue(pathKeyName, out path))
{
renderedPath =
renderedPath.Replace($"%{pathKeyName}%", path)
.Replace(@"\\", @"\");
}
}

return renderedPath;
}

bool ValidatePathExists(string path)
{
if (path == null) throw new ArgumentNullException(nameof(path));

try
{
if (!Directory.Exists(path)) Directory.CreateDirectory(path);

return true;
}
catch (Exception ex)
{
this._logger.Error(ex, "Failure accessing or creating directory {DirectoryPath}", path);
}

return false;
}
}
}
4 changes: 2 additions & 2 deletions src/Papercut.Core/Domain/Paths/MessagePathConfigurator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ public MessagePathConfigurator(IPathTemplatesProvider pathTemplateProvider, ILog

this._logger = logger;
this._pathTemplateProvider = pathTemplateProvider;
this._pathTemplateProvider.PathTemplates.CollectionChanged += this.PathTemplatesCollectionChanged;
this._pathTemplateProvider.MessagePathTemplates.CollectionChanged += this.PathTemplatesCollectionChanged;

this.DefaultSavePath = AppDomain.CurrentDomain.BaseDirectory;
this.RenderLoadPaths();
Expand Down Expand Up @@ -112,7 +112,7 @@ void PathTemplatesCollectionChanged(object sender, NotifyCollectionChangedEventA
void RenderLoadPaths()
{
this.LoadPaths =
this._pathTemplateProvider.PathTemplates.Select(this.RenderPathTemplate)
this._pathTemplateProvider.MessagePathTemplates.Select(this.RenderPathTemplate)
.Where(this.ValidatePathExists)
.ToList();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,11 @@ protected override void Load(ContainerBuilder builder)
.AsSelf()
.SingleInstance();

builder.RegisterType<LoggingPathConfigurator>()
.As<ILoggingPathConfigurator>()
.AsSelf()
.SingleInstance();

builder.RegisterType<JsonSettingStore>()
.As<ISettingStore>()
.OnActivated(
Expand Down
6 changes: 3 additions & 3 deletions src/Papercut.Core/Infrastructure/Logging/RegisterLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ namespace Papercut.Core.Infrastructure.Logging

using Papercut.Common.Domain;
using Papercut.Core.Domain.Application;

using Papercut.Core.Domain.Paths;
using Serilog;
using Serilog.Debugging;

Expand All @@ -45,10 +45,10 @@ internal static void Register(ContainerBuilder builder)
builder.Register(c =>
{
var appMeta = c.Resolve<IAppMeta>();
var loggingPathConfigurator = c.Resolve<ILoggingPathConfigurator>();

string logFilePath = Path.Combine(
AppDomain.CurrentDomain.BaseDirectory,
"Logs",
loggingPathConfigurator.DefaultSavePath,
$"{appMeta.AppName}.log");

// support self-logging
Expand Down
6 changes: 6 additions & 0 deletions src/Papercut.Service/Helpers/PapercutServiceSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,12 @@ public string MessagePath
set { if (MessagePath != value) Settings.Set("MessagePath", value); }
}

public string LoggingPath
{
get => Settings.GetOrSet<string>("LoggingPath", @"%DataDirectory%\Logs;%BaseDirectory%\Logs", "Base path where logs are written.");
set { if (LoggingPath != value) Settings.Set("LoggingPath", value); }
}

public string SeqEndpoint
{
get => Settings.GetOrSet<string>("SeqEndpoint", @"", "Populate with a endpoint if you want to enable SEQ (https://getseq.net/) logging.");
Expand Down
2 changes: 2 additions & 0 deletions src/Papercut.Service/Papercut.Service.Settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
"IPCommUIPort_Description": "## The IP Comm UI listening port (Defaults to 37402).",
"MessagePath": "%DataDirectory%\\Incoming;%BaseDirectory%\\Incoming",
"MessagePath_Description": "## Base path where incoming emails are written.",
"LoggingPath": "%DataDirectory%\\Logs;%BaseDirectory%\\Logs",
"LoggingPath_Description": "## Base path where logs are written.",
"Port": "25",
"Port_Description": "## SMTP Server listening Port. Default is 25.",
"SeqEndpoint": null,
Expand Down
1 change: 0 additions & 1 deletion src/Papercut.Service/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ namespace Papercut.Service
using System.Threading.Tasks;

using Autofac;

using Papercut.Core.Infrastructure.Container;
using Papercut.Core.Infrastructure.Logging;
using Papercut.Service.Services;
Expand Down
13 changes: 10 additions & 3 deletions src/Papercut.Service/Services/ServerPathTemplateProviderService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,20 @@ public class ServerPathTemplateProviderService : IPathTemplatesProvider
{
public ServerPathTemplateProviderService(PapercutServiceSettings serviceSettings)
{
var paths = serviceSettings.MessagePath.Split(';')
var messagePaths = serviceSettings.MessagePath.Split(';')
.Select(s => s.Trim())
.Where(s => !string.IsNullOrWhiteSpace(s));

PathTemplates = new ObservableCollection<string>(paths);
MessagePathTemplates = new ObservableCollection<string>(messagePaths);

var loggingPaths = serviceSettings.LoggingPath.Split(';')
.Select(s => s.Trim())
.Where(s => !string.IsNullOrWhiteSpace(s));

LoggingPathTemplates = new ObservableCollection<string>(loggingPaths);
}

public ObservableCollection<string> PathTemplates { get; private set; }
public ObservableCollection<string> MessagePathTemplates { get; private set; }
public ObservableCollection<string> LoggingPathTemplates { get; private set; }
}
}
3 changes: 3 additions & 0 deletions src/Papercut.UI/App.config
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@
<setting name="MessagePaths" serializeAs="String">
<value>%ApplicationData%\Changemaker Studios\Papercut SMTP;%ApplicationData%\Papercut;%BaseDirectory%\Incoming;%DataDirectory%\Incoming</value>
</setting>
<setting name="LoggingPaths" serializeAs="String">
<value>%ApplicationData%\Changemaker Studios\Papercut SMTP;%ApplicationData%\Papercut;%BaseDirectory%\Logs;%DataDirectory%\Logs</value>
</setting>
</Papercut.Properties.Settings>
</userSettings>
<runtime>
Expand Down
13 changes: 13 additions & 0 deletions src/Papercut.UI/Properties/Settings.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions src/Papercut.UI/Properties/Settings.settings
Original file line number Diff line number Diff line change
Expand Up @@ -44,5 +44,8 @@
<Setting Name="MessagePaths" Type="System.String" Scope="User">
<Value Profile="(Default)">%ApplicationData%\Changemaker Studios\Papercut SMTP;%ApplicationData%\Papercut;%BaseDirectory%\Incoming;%DataDirectory%\Incoming</Value>
</Setting>
<Setting Name="LoggingPaths" Type="System.String" Scope="User">
<Value Profile="(Default)">%ApplicationData%\Changemaker Studios\Papercut SMTP;%ApplicationData%\Papercut;%BaseDirectory%\Logs;%DataDirectory%\Logs</Value>
</Setting>
</Settings>
</SettingsFile>
Loading