I inherited a developer's code and I wanted to convert it to c# since the developer made his library in C#. However the only example I have that shows me how to subscribe to this service is in vba which I dont get how its attaching to it.
namespace exampleExcelAddin.Common.Services
{
public class LogEntry
{
public Type Type;
public string Message;
public IDictionary<string, object> Meta = new Dictionary<string, object>();
}
public interface ILogger
{
void LogMessage(string message);
void LogMessage(Exception exception);
}
public static class Logger
{
readonly static Lazy<ISubject<LogEntry>> _outputStream = new Lazy<ISubject<LogEntry>>(() => {
return new ReplaySubject<LogEntry>();
});
public static ILogger Create(Type loggerType) => new TypedLogger(loggerType, _outputStream.Value);
public static IObservable<LogEntry> Output => _outputStream.Value;
class TypedLogger : ILogger
{
readonly ISubject<LogEntry> outputStream;
readonly Type loggerType;
internal TypedLogger(Type loggerType, ISubject<LogEntry> outputStream)
{
this.loggerType = loggerType;
this.outputStream = outputStream;
}
public void LogMessage(string message)
{
outputStream.OnNext(new LogEntry {
Type = loggerType,
Message = message
});
}
public void LogMessage(Exception exception)
{
var logEntry = new LogEntry {
Type = loggerType,
Message = $"Exception: {exception.Message}"
};
logEntry.Meta.Add("StackTrace", exception.StackTrace);
outputStream.OnNext(logEntry);
}
}
}
}
The working example in vb.net is like so...
Private Shared log As ILogger = Logger.Create(GetType(myRibbon))
Logger.Output.Subscribe(
Sub(entry)
If MySettings.Default.EnableLogging Then
Dim logBuilder As New StringBuilder()
logBuilder.
AppendLine("-------------------------------------------------").
AppendLine($"Type: {entry.Type}").
AppendLine($"Message: {entry.Message}")
For Each meta In entry.Meta
logBuilder.
AppendLine($"Meta-Key: {meta.Key}").
AppendLine($"Meta-Value: {meta.Value}")
Next
logBuilder.
AppendLine("-------------------------------------------------" & Environment.NewLine)
IO.File.AppendAllText(logPath, logBuilder.ToString())
End If
End Sub)
Had some help with converting it and keep getting issues with my lambda expression because it is not a delegate type which I understand but keep hitting a wall. Out my element with how to use this services.
Logger.Output.Subscribe(entry => {
if (Settings.Default.EnableLogging) {
var logBuilder = new StringBuilder();
logBuilder.AppendLine("-------------------------------------------------").AppendLine($"Type: {entry.Type}").AppendLine($"Message: {entry.Message}");
foreach (var meta in entry.Meta) { logBuilder.AppendLine($"Meta-Key: {meta.Key}").AppendLine($"Meta-Value: {meta.Value}"); }
_ = logBuilder.AppendLine("-------------------------------------------------" + Environment.NewLine); System.IO.File.AppendAllText(logPath, logBuilder.ToString());
}
});