Skip to content

Commit

Permalink
fix(Logger): add a Logger class and refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
MingboPeng committed Mar 12, 2024
1 parent 9c84fa4 commit 2a4d404
Show file tree
Hide file tree
Showing 9 changed files with 141 additions and 113 deletions.
57 changes: 19 additions & 38 deletions src/PollinationSDK/Helper/AuthHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,18 +62,16 @@ public static async Task SignInAsync(Action ActionWhenDone = default, bool devEn
var task = PollinationSignInAsync(devEnv);
var authResult = await task;
if (string.IsNullOrEmpty(authResult.IDToken))
throw new ArgumentException($"SignInAsync: Failed to get the Auth token");
throw new ArgumentException($"Failed to get the Auth token");

if (Helper.CurrentUser == null)
throw new ArgumentException($"SignInAsync: Failed to sign in to the Pollination");
throw new ArgumentException($"Failed to sign in to the Pollination");

ActionWhenDone?.Invoke();
}
catch (Exception e)
{
Helper.Logger?.Error(e, "Failed to sign in");
//Console.WriteLine(e.Message);
throw e;
LogHelper.LogThrowError(e);
}

}
Expand All @@ -89,38 +87,30 @@ public static async Task SignInWithApiAuthAsync(string apiAuth, Action ActionWhe
Configuration.Default.BasePath = devEnv ? ApiURL_Dev : ApiURL;
Configuration.Default.AddApiKey("x-pollination-token", apiAuth);
Helper.CurrentUser = Helper.GetUser();
Helper.Logger.Information($"SignInWithApiAuthAsync: logged in as {Helper.CurrentUser.Username}");
LogHelper.LogInfo($"Logged in as {Helper.CurrentUser.Username}");
}
else
{
Helper.Logger.Warning($"SignInWithApiAuthAsync: Invalid apiAuth");
LogHelper.LogWarning($"Invalid apiAuth");
}

ActionWhenDone?.Invoke();
}
catch (Exception e)
{
Helper.Logger?.Error(e, "Failed to sign in");
//Console.WriteLine(e.Message);
throw e;
LogHelper.LogThrowError(e);
}

}


private static async Task<AuthResult> PollinationSignInAsync(bool devEnv = false)
{
if (!HttpListener.IsSupported)
{
Helper.Logger.Error($"PollinationSignInAsync: HttpListener is not supported on this system");
throw new ArgumentException("PollinationSignIn is not supported on this system");
}
if (!HttpListener.IsSupported)
LogHelper.LogThrowError($"HttpListener is not supported on this system");

if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
Helper.Logger.Error($"PollinationSignInAsync: Network is not available, please double check with your connection or firewall!");
throw new ArgumentException("Network is not available, please double check with your connection or firewall!");
}
LogHelper.LogThrowError($"Network is not available, please double check with your connection or firewall!");

var redirectUrl = "http://localhost:8645/";
var loginUrl = devEnv ? LoginURL_Dev : LoginURL;
Expand All @@ -140,16 +130,10 @@ private static async Task<AuthResult> PollinationSignInAsync(bool devEnv = false
catch (HttpListenerException e)
{
//it is already listening the port, but users didn't login
if (e.ErrorCode == 183)
{
Console.WriteLine(e.Message);
Helper.Logger.Warning($"PollinationSignInAsync: it is still waiting for users to login from last time.\n{e.Message}");
}
else
{
Helper.Logger.Error($"PollinationSignInAsync: Failed to start the listener.\n{e.Message}");
throw e;
}
if (e.ErrorCode == 183)
LogHelper.LogWarning($"It is still waiting for users to login from last time.\n{e.Message}");
else
LogHelper.LogThrowError($"Failed to start the listener.\n{e.Message}");

}

Expand All @@ -159,7 +143,7 @@ private static async Task<AuthResult> PollinationSignInAsync(bool devEnv = false
UseShellExecute = true
};
System.Diagnostics.Process.Start(psi);
Helper.Logger.Information($"PollinationSignInAsync: login from {loginUrl}");
LogHelper.LogInfo($"Login from {loginUrl}");

// wait for the authorization response.
var context = await listener.GetContextAsync();
Expand All @@ -168,11 +152,8 @@ private static async Task<AuthResult> PollinationSignInAsync(bool devEnv = false
var response = context.Response;

var returnUrl = request.RawUrl.Contains("?token=") ? request.RawUrl : request.UrlReferrer?.PathAndQuery;
if (string.IsNullOrEmpty(returnUrl))
{
Helper.Logger.Error($"PollinationSignInAsync: Failed to authorize the login: \n{request.RawUrl}");
throw new ArgumentException($"Failed to authorize the login: \n{request.RawUrl}");
}
if (string.IsNullOrEmpty(returnUrl))
LogHelper.LogThrowError($"Failed to authorize the login: \n{request.RawUrl}");

var auth = AuthResult.From(request.QueryString);
var loggedIn = CheckGetUser(auth, out var error, devEnv);
Expand All @@ -195,7 +176,7 @@ private static async Task<AuthResult> PollinationSignInAsync(bool devEnv = false
responseOutput.Flush();
responseOutput.Close();

Helper.Logger.Information($"PollinationSignInAsync: closing the listener");
LogHelper.LogInfo($"Closed listener");

return auth;
}
Expand All @@ -221,7 +202,7 @@ private static bool CheckGetUser(AuthResult auth, out string errorMessage, bool
refreshToken: auth.RefreshToken
);
Helper.CurrentUser = Helper.GetUser();
Helper.Logger?.Information($"CheckGetUser: logged in as {Helper.CurrentUser.Username}");
LogHelper.LogInfo($"Logged in as {Helper.CurrentUser.Username}");

return true;

Expand All @@ -230,7 +211,7 @@ private static bool CheckGetUser(AuthResult auth, out string errorMessage, bool
{
Configuration.Default.TokenRepo = null;
Helper.CurrentUser = null;
Helper.Logger?.Error(e, $"CheckGetUser()");
LogHelper.LogError(e);
errorMessage = e.Message;
return false;
//throw;
Expand Down
5 changes: 2 additions & 3 deletions src/PollinationSDK/Helper/HandlerChecker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public object CheckWithHandlers(object inputData, List<IOAliasHandler> handlers)
}
catch (Exception e)
{
Helper.Logger?.Error(e, $"PollinationSDK: error.");
LogHelper.LogError(e);
errors.Add($"{e?.Message}{Environment.NewLine}From {item.Function}(Handler-{item.Language})");
break;
//throw;
Expand Down Expand Up @@ -158,8 +158,7 @@ private static Assembly LoadDll(string csProjName)
}
catch (Exception ex)
{
Helper.Logger?.Error(ex, $"PollinationSDK: cannot find handler libraries.");
throw new System.IO.FileNotFoundException($"Cannot find handler libraries.\n{ex.Message}");
throw LogHelper.LogReturnError(ex, $"PollinationSDK: cannot find handler libraries.");
}
}

Expand Down
41 changes: 19 additions & 22 deletions src/PollinationSDK/Helper/Helper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ public static Project GetAProject(string userName, string projectName)
var res = api.CreateProject(userName, new ProjectCreate(projectName, _public: ifPublic));
return GetAProject(userName, projectName);
}
Helper.Logger.Error(e, $"GetAProject: failed to get the project {userName}/{projectName}");
LogHelper.LogError(e, $"Failed to get the project {userName}/{projectName}");
throw e;
}

Expand All @@ -90,8 +90,8 @@ public static Project GetWritableProject(string projectSlug)

public static async Task<bool> UploadDirectoryAsync(Project project, string directory, Action<int> reportProgressAction = default, CancellationToken cancellationToken = default)
{
Helper.Logger.Information($"Uploading a directory {directory}");
Helper.Logger.Information($"Timeout: {Configuration.Default.Timeout}");
LogHelper.LogInfo($"Uploading a directory {directory}");
LogHelper.LogInfo($"Timeout: {Configuration.Default.Timeout}");

var files = Directory.GetFiles(directory, "*", SearchOption.AllDirectories);
var api = new ArtifactsApi();
Expand All @@ -100,7 +100,7 @@ public static async Task<bool> UploadDirectoryAsync(Project project, string dire
var tasks = files.Select(_ => UploadArtifactAsync(api, project, _, _.Replace(directory, ""))).ToList();
var total = files.Count();

Helper.Logger.Information($"UploadDirectoryAsync: Uploading {total} assets for project {project.Name}");
LogHelper.LogInfo($"Uploading {total} assets for project {project.Name}");


var finishedPercent = 0;
Expand All @@ -111,15 +111,15 @@ public static async Task<bool> UploadDirectoryAsync(Project project, string dire
// canceled by user
if (cancellationToken.IsCancellationRequested)
{
Helper.Logger.Information($"Canceled uploading by user");
LogHelper.LogInfo($"Canceled uploading by user");
break;
}

var finishedTask = await Task.WhenAny(tasks);

if (finishedTask.IsFaulted || finishedTask.Exception != null)
{
Helper.Logger.Error($"Upload exception: {finishedTask.Exception}");
LogHelper.LogError($"Upload exception: {finishedTask.Exception}");
throw finishedTask.Exception;
}

Expand All @@ -130,7 +130,7 @@ public static async Task<bool> UploadDirectoryAsync(Project project, string dire
reportProgressAction?.Invoke(finishedPercent);

}
Helper.Logger.Information($"UploadDirectoryAsync: Finished uploading assets for project {project.Name}");
LogHelper.LogInfo($"Finished uploading assets for project {project.Name}");

// canceled by user
if (cancellationToken.IsCancellationRequested) return false;
Expand Down Expand Up @@ -171,18 +171,18 @@ public static async Task<bool> UploadArtifactAsync(ArtifactsApi api, Project pro

restRequest.AddFile("file", filePath);

Helper.Logger.Information($"Started upload of {relativePath}");
LogHelper.LogInfo($"Started upload of {relativePath}");
var response = await restClient.ExecuteAsync(restRequest);

if (response.StatusCode == HttpStatusCode.NoContent)
{
Helper.Logger.Information($"UploadArtifaceAsync: Done uploading {fileRelativePath}");
LogHelper.LogInfo($"Done uploading {fileRelativePath}");
return true;
}
else
{
Helper.Logger.Information($"UploadArtifaceAsync: Received response code: {response.StatusCode}");
Helper.Logger.Information($"{response.Content}");
LogHelper.LogInfo($"Received response code: {response.StatusCode}");
LogHelper.LogInfo($"{response.Content}");
}
return false;
}
Expand Down Expand Up @@ -504,13 +504,13 @@ public static async Task<string> DownloadArtifactAsync(ArtifactsApi api, string

var url = (await api.DownloadArtifactAsync(projOwner, projName, fileRelativePath))?.ToString();

Helper.Logger.Information($"DownloadArtifactAsync: downloading {fileRelativePath} from \n -{url}\n");
LogHelper.LogInfo($"Downloading {fileRelativePath} from \n -{url}\n");
// get relative path correct
saveAsDir = Path.GetDirectoryName(Path.Combine(saveAsDir, relativePath));
saveAsDir = Path.GetFullPath(saveAsDir);
var path = await Helper.DownloadUrlAsync(url.ToString(), saveAsDir, reportProgressAction, null, cancelToken);

Helper.Logger.Information($"DownloadArtifactAsync: saved {fileRelativePath} to {path}");
LogHelper.LogInfo($"Saved {fileRelativePath} to {path}");
return path;
}

Expand All @@ -522,13 +522,13 @@ public static async Task<string> DownloadArtifactAsync(JobsApi api, string projO

var url = (await api.DownloadJobArtifactAsync(projOwner, projName, jobId, fileRelativePath, cancelToken))?.ToString();

Helper.Logger.Information($"DownloadJobArtifactAsync: downloading {fileRelativePath} from \n -{url}\n");
LogHelper.LogInfo($"Downloading {fileRelativePath} from \n -{url}\n");
// get relative path correct
saveAsDir = Path.GetDirectoryName(Path.Combine(saveAsDir, relativePath));
saveAsDir = Path.GetFullPath(saveAsDir);
var path = await Helper.DownloadUrlAsync(url.ToString(), saveAsDir, reportProgressAction, null, cancelToken);

Helper.Logger.Information($"DownloadJobArtifactAsync: saved {fileRelativePath} to {path}");
LogHelper.LogInfo($"Saved {fileRelativePath} to {path}");
return path;
}

Expand Down Expand Up @@ -617,7 +617,7 @@ public static async Task<string> DownloadUrlAsync(string url, string saveAsDir,

Directory.CreateDirectory(saveAsDir);
var file = Path.Combine(saveAsDir, fileName);
Helper.Logger.Information($"DownloadUrlAsync: downloading {url}");
LogHelper.LogInfo($"Downloading {url}");
using (WebClient wc = new WebClient())
{
var prog = 0;
Expand All @@ -640,7 +640,7 @@ public static async Task<string> DownloadUrlAsync(string url, string saveAsDir,
await t;
if (t.IsFaulted && t.Exception != null)
throw t.Exception;
Helper.Logger.Information($"DownloadUrlAsync: saved {fileName} to {file}");
LogHelper.LogInfo($"Saved {fileName} to {file}");
}
catch (WebException ex) when (ex.Status == WebExceptionStatus.RequestCanceled)
{
Expand All @@ -660,9 +660,7 @@ public static async Task<string> DownloadUrlAsync(string url, string saveAsDir,

if (!File.Exists(file))
{
var e = new ArgumentException($"Failed to download {fileName}");
Helper.Logger.Error(e, $"DownloadFromUrlAsync: error");
throw e;
throw LogHelper.LogReturnError($"Failed to download {fileName}");
}
var outputDirOrFile = file;

Expand All @@ -673,8 +671,7 @@ public static async Task<string> DownloadUrlAsync(string url, string saveAsDir,
}
catch (Exception e)
{
Helper.Logger.Error(e, $"DownloadFromUrlAsync: Unable to unzip file {Path.GetFileName(file)}");
throw new ArgumentException($"Failed to unzip file {Path.GetFileName(file)}.\n -{e.Message}");
throw LogHelper.LogReturnError(e, $"Unable to unzip file {Path.GetFileName(file)}");
}

return outputDirOrFile;
Expand Down
67 changes: 67 additions & 0 deletions src/PollinationSDK/Helper/Logger.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
using System.Runtime.CompilerServices;
using System;

namespace PollinationSDK
{
public static class LogHelper
{
public static Serilog.ILogger Logger
{
get => Helper.Logger;
set => Helper.Logger = value;
}

public static void LogInfo(string message, [CallerMemberName] string memberName = "")
{
Logger?.Information("{memberName}:{message}", memberName, message);
}
public static void LogWarning(string message, [CallerMemberName] string memberName = "")
{
Logger?.Warning("{memberName}:{message}", memberName, message);
}

public static void LogError(string ex, [CallerMemberName] string memberName = "")
{
Logger?.Error("{memberName}:{ex}", memberName, ex);
}

public static void LogError(Exception ex, [CallerMemberName] string memberName = "")
{
Logger?.Error(ex, "{memberName}", memberName);
}

/// <summary>
/// Log and throw the error
/// </summary>
/// <param name="ex"></param>
/// <param name="memberName"></param>
public static void LogThrowError(string ex, [CallerMemberName] string memberName = "")
{
LogThrowError(new ArgumentException(ex), memberName);
}

/// <summary>
/// Log and throw the error
/// </summary>
/// <param name="ex"></param>
/// <param name="memberName"></param>
public static void LogThrowError(Exception ex, [CallerMemberName] string memberName = "")
{
Logger?.Error(ex, "{memberName}", memberName);
throw ex;
}

public static Exception LogReturnError(string ex, [CallerMemberName] string memberName = "")
{
return LogReturnError(new ArgumentException(ex), memberName);
}

public static Exception LogReturnError(Exception ex, [CallerMemberName] string memberName = "")
{
Logger?.Error(ex, "{memberName}", memberName);
return ex;
}

}

}
Loading

0 comments on commit 2a4d404

Please sign in to comment.