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

Space lab fixes #4

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
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
223 changes: 120 additions & 103 deletions SharpBoss.Logging/Logger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,110 +6,127 @@
using NLog.Config;
using NLog.Targets;

namespace SharpBoss.Logging {
/// <summary>
/// Logger class
/// </summary>
public static class Logger {
private static readonly string _datePattern = "yyyy-MM-dd";
private static readonly string _filenamePattern = "sharpboss_{0}.txt";
private static readonly string _environmentVariable = "SHARPBOSS_CONFIG_FILENAME";
private static readonly string _configKey = "SHARPBOSS_CONFIG_FILENAME";

/// <summary>
/// Retrieve Logger
/// </summary>
/// <returns>ILogger</returns>
private static ILogger GetLogger () {
var stackFrame = new StackFrame (2, true);
var method = stackFrame.GetMethod ();
var assembly = method.DeclaringType;

LogManager.Configuration = GetConfig ();

var loggingName = string.Format ("{0}::{1}", assembly.FullName, method.Name);

return LogManager.GetLogger (loggingName);
}

/// <summary>
/// Retrieve filename for Logging output
/// </summary>
/// <returns>Retrieve filename for Logging output</returns>
private static string GetFileName () {
var dateTime = DateTime.Now;
var filename = string.Format (_filenamePattern, dateTime.ToString (_datePattern));
var environmentVariable = Environment.GetEnvironmentVariable (_environmentVariable);
var configValue = ConfigurationManager.AppSettings[_configKey];

if (environmentVariable != null) {
return environmentVariable;
} else if (configValue != null) {
return configValue;
}

return filename;
}

/// <summary>
/// Get configuration for Log target
/// </summary>
/// <returns>NLog Configuration</returns>
private static LoggingConfiguration GetConfig () {
var config = new LoggingConfiguration ();
var target = new FileTarget {
FileName = GetFileName (),
Layout = "${longdate} ${level:lowercase=true} [${logger}] ${message}",
};

config.AddRuleForAllLevels (target);

return config;
}

/// <summary>
/// Retrieve message with format
/// </summary>
/// <param name="message">Message to log</param>
/// <returns>Formatted message</returns>
private static string GetMessage (string message) {
return string.Format ("{0}", message);
}

/// <summary>
/// Log message with info level
/// </summary>
/// <param name="message">Message to log</param>
public static void Info (string message) {
var logger = GetLogger ();
logger.Info (GetMessage (message));
}

/// <summary>
/// Log message with debug level
/// </summary>
/// <param name="message">Message to log</param>
public static void Debug (string message) {
var logger = GetLogger ();
logger.Debug (GetMessage (message));
}

/// <summary>
/// Log message with warning level
/// </summary>
/// <param name="message">Message to log</param>
public static void Warn (string message) {
var logger = GetLogger ();
logger.Warn (GetMessage (message));
}

namespace SharpBoss.Logging
{
/// <summary>
/// Log message with error level
/// Logger class
/// </summary>
/// <param name="message">Message to log</param>
public static void Error (string message) {
var logger = GetLogger ();
logger.Error (GetMessage (message));
public static class Logger
{
private static readonly string _datePattern = "yyyy-MM-dd";
private static readonly string _filenamePattern = "sharpboss_{0}.txt";
private static readonly string _environmentVariable = "SHARPBOSS_CONFIG_FILENAME";
private static readonly string _configKey = "SHARPBOSS_CONFIG_FILENAME";

static readonly ILogger Log = LogManager.GetCurrentClassLogger();

/// <summary>
/// Retrieve Logger
/// </summary>
/// <returns>ILogger</returns>
private static ILogger GetLogger()
{
//var stackFrame = new StackFrame (2, true);
//var method = stackFrame.GetMethod ();
//var assembly = method.DeclaringType;

//LogManager.Configuration = GetConfig ();

//var loggingName = string.Format ("{0}::{1}", assembly.FullName, method.Name);

//return LogManager.GetLogger (loggingName);
return Log;
}

/// <summary>
/// Retrieve filename for Logging output
/// </summary>
/// <returns>Retrieve filename for Logging output</returns>
private static string GetFileName()
{
var dateTime = DateTime.Now;
var filename = string.Format(_filenamePattern, dateTime.ToString(_datePattern));
var environmentVariable = Environment.GetEnvironmentVariable(_environmentVariable);
var configValue = ConfigurationManager.AppSettings[_configKey];

if (environmentVariable != null)
{
return environmentVariable;
}
else if (configValue != null)
{
return configValue;
}

return filename;
}

/// <summary>
/// Get configuration for Log target
/// </summary>
/// <returns>NLog Configuration</returns>
private static LoggingConfiguration GetConfig()
{
var config = new LoggingConfiguration();
var target = new FileTarget
{
FileName = GetFileName(),
Layout = "${longdate} ${level:lowercase=true} [${logger}] ${message}",
};

config.AddRuleForAllLevels(target);

return config;
}

/// <summary>
/// Retrieve message with format
/// </summary>
/// <param name="message">Message to log</param>
/// <returns>Formatted message</returns>
private static string GetMessage(string message)
{
return string.Format("{0}", message);
}

/// <summary>
/// Log message with info level
/// </summary>
/// <param name="message">Message to log</param>
public static void Info(string message)
{
var logger = GetLogger();
logger.Info(GetMessage(message));
}

/// <summary>
/// Log message with debug level
/// </summary>
/// <param name="message">Message to log</param>
public static void Debug(string message)
{
var logger = GetLogger();
logger.Debug(GetMessage(message));
}

/// <summary>
/// Log message with warning level
/// </summary>
/// <param name="message">Message to log</param>
public static void Warn(string message)
{
var logger = GetLogger();
logger.Warn(GetMessage(message));
}

/// <summary>
/// Log message with error level
/// </summary>
/// <param name="message">Message to log</param>
public static void Error(string message)
{
var logger = GetLogger();
logger.Error(GetMessage(message));
}
}
}
}
6 changes: 5 additions & 1 deletion SharpBoss.Logging/SharpBoss.Logging.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<TargetFramework>net48</TargetFramework>
</PropertyGroup>

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<PlatformTarget>x64</PlatformTarget>
</PropertyGroup>

<ItemGroup>
Expand Down
6 changes: 5 additions & 1 deletion SharpBoss.Tests/SharpBoss.Tests.csproj
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<TargetFramework>net48</TargetFramework>

<IsPackable>false</IsPackable>
</PropertyGroup>

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<PlatformTarget>x64</PlatformTarget>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="nunit" Version="3.12.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.15.1" />
Expand Down
37 changes: 36 additions & 1 deletion SharpBoss/Models/RestRequest.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using EmbedIO;
using System;
using System.Collections.Specialized;
using System.IO;
using System.Net;
Expand Down Expand Up @@ -131,6 +132,40 @@ public class RestRequest {
/// </summary>
public Uri UrlReferrer { get { return this._urlReferrer; } }

public RestRequest(IHttpContext context)
{
this._userAgent = context.Request.UserAgent; // request.UserAgent;
this._userHostAddress = context.Request.RemoteEndPoint.Address.ToString();
this._userHostName = context.Request.RemoteEndPoint.Address.ToString();
//this._userLanguages = context.Request.UserLanguages;
this._url = context.Request.Url;
this._urlReferrer = context.Request.UrlReferrer;
//this._acceptTypes = context.Request.AcceptTypes;
this._contentEncoding = context.Request.ContentEncoding;
this._contentLength = context.Request.ContentLength64;
this._contentType = context.Request.ContentType;
//this._cookies = context.Request.Cookies;
this._httpMethod = context.Request.HttpMethod;
this._isAuthenticated = context.Request.IsAuthenticated;
this._isLocal = context.Request.IsLocal;
this._isSecureConnection = context.Request.IsSecureConnection;
this._isWebSocketRequest = context.Request.IsWebSocketRequest;
this._keepAlive = context.Request.KeepAlive;
this._queryString = context.Request.QueryString;
this._rawUrl = context.Request.RawUrl;

if (context.Request.HasEntityBody)
{
using (var body = context.Request.InputStream)
{
using (var reader = new StreamReader(body, context.Request.ContentEncoding))
{
this._body = reader.ReadToEnd();
}
}
}
}

/// <summary>
/// Instantiate a new request with listener
/// </summary>
Expand Down
12 changes: 10 additions & 2 deletions SharpBoss/Processors/RestProcessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
using System.Net;
using System.Reflection;
using System.Text.Json;

using System.Text.Json.Serialization;
using SharpBoss.Attributes;
using SharpBoss.Attributes.Methods;
using SharpBoss.Exceptions;
Expand All @@ -25,6 +25,7 @@ public class RestProcessor {
private Dictionary<string, RestProxy> _proxies;
private Dictionary<string, IRestExceptionHandler> _exceptionHandlers;
private Dictionary<string, object> _injectables;
private JsonSerializerOptions _serializerOptions;

/// <summary>
/// Create new REST processor
Expand All @@ -34,6 +35,7 @@ public RestProcessor () {
this._proxies = new Dictionary<string, RestProxy> ();
this._exceptionHandlers = new Dictionary<string, IRestExceptionHandler> ();
this._injectables = new Dictionary<string, object> ();
this._serializerOptions = new JsonSerializerOptions() { WriteIndented = true };
}

/// <summary>
Expand All @@ -49,6 +51,12 @@ public void Init (Assembly runningAssembly, string nameSpace) {
foreach (var type in types) {
var restAttribute = type.GetCustomAttribute (typeof (REST));

if (typeof(JsonConverter<>).IsAssignableFrom(type) || typeof(JsonConverter).IsAssignableFrom(type))
{
Logger.Info($"Found JsonConverter {type.Name}");
_serializerOptions.Converters.Add((JsonConverter)Activator.CreateInstance(type));
}

if (restAttribute != null) {
Logger.Info ("Found REST class " + type.Name);
var rest = (REST)restAttribute;
Expand Down Expand Up @@ -137,7 +145,7 @@ public RestResponse Process (string path, string method, RestRequest request) {
if (response is string) {
return new RestResponse ((string)response);
} else {
return new RestResponse (JsonSerializer.Serialize (response), "application/json");
return new RestResponse (JsonSerializer.Serialize (response, _serializerOptions), "application/json");
}
} else {
return new RestResponse ("Not found", "text/plain", HttpStatusCode.NotFound);
Expand Down
Loading
Loading