Skip to content

Commit 2a4d404

Browse files
committed
fix(Logger): add a Logger class and refactor
1 parent 9c84fa4 commit 2a4d404

File tree

9 files changed

+141
-113
lines changed

9 files changed

+141
-113
lines changed

src/PollinationSDK/Helper/AuthHelper.cs

+19-38
Original file line numberDiff line numberDiff line change
@@ -62,18 +62,16 @@ public static async Task SignInAsync(Action ActionWhenDone = default, bool devEn
6262
var task = PollinationSignInAsync(devEnv);
6363
var authResult = await task;
6464
if (string.IsNullOrEmpty(authResult.IDToken))
65-
throw new ArgumentException($"SignInAsync: Failed to get the Auth token");
65+
throw new ArgumentException($"Failed to get the Auth token");
6666

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

7070
ActionWhenDone?.Invoke();
7171
}
7272
catch (Exception e)
7373
{
74-
Helper.Logger?.Error(e, "Failed to sign in");
75-
//Console.WriteLine(e.Message);
76-
throw e;
74+
LogHelper.LogThrowError(e);
7775
}
7876

7977
}
@@ -89,38 +87,30 @@ public static async Task SignInWithApiAuthAsync(string apiAuth, Action ActionWhe
8987
Configuration.Default.BasePath = devEnv ? ApiURL_Dev : ApiURL;
9088
Configuration.Default.AddApiKey("x-pollination-token", apiAuth);
9189
Helper.CurrentUser = Helper.GetUser();
92-
Helper.Logger.Information($"SignInWithApiAuthAsync: logged in as {Helper.CurrentUser.Username}");
90+
LogHelper.LogInfo($"Logged in as {Helper.CurrentUser.Username}");
9391
}
9492
else
9593
{
96-
Helper.Logger.Warning($"SignInWithApiAuthAsync: Invalid apiAuth");
94+
LogHelper.LogWarning($"Invalid apiAuth");
9795
}
9896

9997
ActionWhenDone?.Invoke();
10098
}
10199
catch (Exception e)
102100
{
103-
Helper.Logger?.Error(e, "Failed to sign in");
104-
//Console.WriteLine(e.Message);
105-
throw e;
101+
LogHelper.LogThrowError(e);
106102
}
107103

108104
}
109105

110106

111107
private static async Task<AuthResult> PollinationSignInAsync(bool devEnv = false)
112108
{
113-
if (!HttpListener.IsSupported)
114-
{
115-
Helper.Logger.Error($"PollinationSignInAsync: HttpListener is not supported on this system");
116-
throw new ArgumentException("PollinationSignIn is not supported on this system");
117-
}
109+
if (!HttpListener.IsSupported)
110+
LogHelper.LogThrowError($"HttpListener is not supported on this system");
118111

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

125115
var redirectUrl = "http://localhost:8645/";
126116
var loginUrl = devEnv ? LoginURL_Dev : LoginURL;
@@ -140,16 +130,10 @@ private static async Task<AuthResult> PollinationSignInAsync(bool devEnv = false
140130
catch (HttpListenerException e)
141131
{
142132
//it is already listening the port, but users didn't login
143-
if (e.ErrorCode == 183)
144-
{
145-
Console.WriteLine(e.Message);
146-
Helper.Logger.Warning($"PollinationSignInAsync: it is still waiting for users to login from last time.\n{e.Message}");
147-
}
148-
else
149-
{
150-
Helper.Logger.Error($"PollinationSignInAsync: Failed to start the listener.\n{e.Message}");
151-
throw e;
152-
}
133+
if (e.ErrorCode == 183)
134+
LogHelper.LogWarning($"It is still waiting for users to login from last time.\n{e.Message}");
135+
else
136+
LogHelper.LogThrowError($"Failed to start the listener.\n{e.Message}");
153137

154138
}
155139

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

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

170154
var returnUrl = request.RawUrl.Contains("?token=") ? request.RawUrl : request.UrlReferrer?.PathAndQuery;
171-
if (string.IsNullOrEmpty(returnUrl))
172-
{
173-
Helper.Logger.Error($"PollinationSignInAsync: Failed to authorize the login: \n{request.RawUrl}");
174-
throw new ArgumentException($"Failed to authorize the login: \n{request.RawUrl}");
175-
}
155+
if (string.IsNullOrEmpty(returnUrl))
156+
LogHelper.LogThrowError($"Failed to authorize the login: \n{request.RawUrl}");
176157

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

198-
Helper.Logger.Information($"PollinationSignInAsync: closing the listener");
179+
LogHelper.LogInfo($"Closed listener");
199180

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

226207
return true;
227208

@@ -230,7 +211,7 @@ private static bool CheckGetUser(AuthResult auth, out string errorMessage, bool
230211
{
231212
Configuration.Default.TokenRepo = null;
232213
Helper.CurrentUser = null;
233-
Helper.Logger?.Error(e, $"CheckGetUser()");
214+
LogHelper.LogError(e);
234215
errorMessage = e.Message;
235216
return false;
236217
//throw;

src/PollinationSDK/Helper/HandlerChecker.cs

+2-3
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ public object CheckWithHandlers(object inputData, List<IOAliasHandler> handlers)
3333
}
3434
catch (Exception e)
3535
{
36-
Helper.Logger?.Error(e, $"PollinationSDK: error.");
36+
LogHelper.LogError(e);
3737
errors.Add($"{e?.Message}{Environment.NewLine}From {item.Function}(Handler-{item.Language})");
3838
break;
3939
//throw;
@@ -158,8 +158,7 @@ private static Assembly LoadDll(string csProjName)
158158
}
159159
catch (Exception ex)
160160
{
161-
Helper.Logger?.Error(ex, $"PollinationSDK: cannot find handler libraries.");
162-
throw new System.IO.FileNotFoundException($"Cannot find handler libraries.\n{ex.Message}");
161+
throw LogHelper.LogReturnError(ex, $"PollinationSDK: cannot find handler libraries.");
163162
}
164163
}
165164

src/PollinationSDK/Helper/Helper.cs

+19-22
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ public static Project GetAProject(string userName, string projectName)
7272
var res = api.CreateProject(userName, new ProjectCreate(projectName, _public: ifPublic));
7373
return GetAProject(userName, projectName);
7474
}
75-
Helper.Logger.Error(e, $"GetAProject: failed to get the project {userName}/{projectName}");
75+
LogHelper.LogError(e, $"Failed to get the project {userName}/{projectName}");
7676
throw e;
7777
}
7878

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

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

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

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

105105

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

118118
var finishedTask = await Task.WhenAny(tasks);
119119

120120
if (finishedTask.IsFaulted || finishedTask.Exception != null)
121121
{
122-
Helper.Logger.Error($"Upload exception: {finishedTask.Exception}");
122+
LogHelper.LogError($"Upload exception: {finishedTask.Exception}");
123123
throw finishedTask.Exception;
124124
}
125125

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

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

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

172172
restRequest.AddFile("file", filePath);
173173

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

177177
if (response.StatusCode == HttpStatusCode.NoContent)
178178
{
179-
Helper.Logger.Information($"UploadArtifaceAsync: Done uploading {fileRelativePath}");
179+
LogHelper.LogInfo($"Done uploading {fileRelativePath}");
180180
return true;
181181
}
182182
else
183183
{
184-
Helper.Logger.Information($"UploadArtifaceAsync: Received response code: {response.StatusCode}");
185-
Helper.Logger.Information($"{response.Content}");
184+
LogHelper.LogInfo($"Received response code: {response.StatusCode}");
185+
LogHelper.LogInfo($"{response.Content}");
186186
}
187187
return false;
188188
}
@@ -504,13 +504,13 @@ public static async Task<string> DownloadArtifactAsync(ArtifactsApi api, string
504504

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

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

513-
Helper.Logger.Information($"DownloadArtifactAsync: saved {fileRelativePath} to {path}");
513+
LogHelper.LogInfo($"Saved {fileRelativePath} to {path}");
514514
return path;
515515
}
516516

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

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

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

531-
Helper.Logger.Information($"DownloadJobArtifactAsync: saved {fileRelativePath} to {path}");
531+
LogHelper.LogInfo($"Saved {fileRelativePath} to {path}");
532532
return path;
533533
}
534534

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

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

661661
if (!File.Exists(file))
662662
{
663-
var e = new ArgumentException($"Failed to download {fileName}");
664-
Helper.Logger.Error(e, $"DownloadFromUrlAsync: error");
665-
throw e;
663+
throw LogHelper.LogReturnError($"Failed to download {fileName}");
666664
}
667665
var outputDirOrFile = file;
668666

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

680677
return outputDirOrFile;

src/PollinationSDK/Helper/Logger.cs

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
using System.Runtime.CompilerServices;
2+
using System;
3+
4+
namespace PollinationSDK
5+
{
6+
public static class LogHelper
7+
{
8+
public static Serilog.ILogger Logger
9+
{
10+
get => Helper.Logger;
11+
set => Helper.Logger = value;
12+
}
13+
14+
public static void LogInfo(string message, [CallerMemberName] string memberName = "")
15+
{
16+
Logger?.Information("{memberName}:{message}", memberName, message);
17+
}
18+
public static void LogWarning(string message, [CallerMemberName] string memberName = "")
19+
{
20+
Logger?.Warning("{memberName}:{message}", memberName, message);
21+
}
22+
23+
public static void LogError(string ex, [CallerMemberName] string memberName = "")
24+
{
25+
Logger?.Error("{memberName}:{ex}", memberName, ex);
26+
}
27+
28+
public static void LogError(Exception ex, [CallerMemberName] string memberName = "")
29+
{
30+
Logger?.Error(ex, "{memberName}", memberName);
31+
}
32+
33+
/// <summary>
34+
/// Log and throw the error
35+
/// </summary>
36+
/// <param name="ex"></param>
37+
/// <param name="memberName"></param>
38+
public static void LogThrowError(string ex, [CallerMemberName] string memberName = "")
39+
{
40+
LogThrowError(new ArgumentException(ex), memberName);
41+
}
42+
43+
/// <summary>
44+
/// Log and throw the error
45+
/// </summary>
46+
/// <param name="ex"></param>
47+
/// <param name="memberName"></param>
48+
public static void LogThrowError(Exception ex, [CallerMemberName] string memberName = "")
49+
{
50+
Logger?.Error(ex, "{memberName}", memberName);
51+
throw ex;
52+
}
53+
54+
public static Exception LogReturnError(string ex, [CallerMemberName] string memberName = "")
55+
{
56+
return LogReturnError(new ArgumentException(ex), memberName);
57+
}
58+
59+
public static Exception LogReturnError(Exception ex, [CallerMemberName] string memberName = "")
60+
{
61+
Logger?.Error(ex, "{memberName}", memberName);
62+
return ex;
63+
}
64+
65+
}
66+
67+
}

0 commit comments

Comments
 (0)