Skip to content

Commit 4ed61b1

Browse files
committed
feat(logger): work with the new Pollination.Logger
1 parent 374ee8a commit 4ed61b1

13 files changed

+173
-183
lines changed

src/PollinationSDK/Helper/AuthHelper.cs

+15-13
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,13 @@
44
using System.Threading.Tasks;
55
using System.Collections.Specialized;
66
using PollinationSDK.Client;
7+
using Pollination;
78

89
namespace PollinationSDK
910
{
1011
public static class AuthHelper
1112
{
13+
private static Microsoft.Extensions.Logging.ILogger Logger => LogUtils.GetLogger(nameof(AuthHelper));
1214
public struct AuthResult
1315
{
1416
public string IDToken;
@@ -71,7 +73,7 @@ public static async Task SignInAsync(Action ActionWhenDone = default, bool devEn
7173
}
7274
catch (Exception e)
7375
{
74-
LogHelper.LogThrowError(e);
76+
Logger.ThrowError(e);
7577
}
7678

7779
}
@@ -87,18 +89,18 @@ public static async Task SignInWithApiAuthAsync(string apiAuth, Action ActionWhe
8789
Configuration.Default.BasePath = devEnv ? ApiURL_Dev : ApiURL;
8890
Configuration.Default.AddApiKey("x-pollination-token", apiAuth);
8991
Helper.CurrentUser = Helper.GetUser();
90-
LogHelper.LogInfo($"Logged in as {Helper.CurrentUser.Username}");
92+
Logger.Info($"Logged in as {Helper.CurrentUser.Username}");
9193
}
9294
else
9395
{
94-
LogHelper.LogWarning($"Invalid apiAuth");
96+
Logger.Warning($"Invalid apiAuth");
9597
}
9698

9799
ActionWhenDone?.Invoke();
98100
}
99101
catch (Exception e)
100102
{
101-
LogHelper.LogThrowError(e);
103+
Logger.ThrowError(e);
102104
}
103105

104106
}
@@ -107,10 +109,10 @@ public static async Task SignInWithApiAuthAsync(string apiAuth, Action ActionWhe
107109
private static async Task<AuthResult> PollinationSignInAsync(bool devEnv = false)
108110
{
109111
if (!HttpListener.IsSupported)
110-
LogHelper.LogThrowError($"HttpListener is not supported on this system");
112+
Logger.ThrowError($"HttpListener is not supported on this system");
111113

112114
if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
113-
LogHelper.LogThrowError($"Network is not available, please double check with your connection or firewall!");
115+
Logger.ThrowError($"Network is not available, please double check with your connection or firewall!");
114116

115117
var redirectUrl = "http://localhost:8645/";
116118
var loginUrl = devEnv ? LoginURL_Dev : LoginURL;
@@ -131,9 +133,9 @@ private static async Task<AuthResult> PollinationSignInAsync(bool devEnv = false
131133
{
132134
//it is already listening the port, but users didn't login
133135
if (e.ErrorCode == 183)
134-
LogHelper.LogWarning($"It is still waiting for users to login from last time.\n{e.Message}");
136+
Logger.Warning($"It is still waiting for users to login from last time.\n{e.Message}");
135137
else
136-
LogHelper.LogThrowError($"Failed to start the listener.\n{e.Message}");
138+
Logger.ThrowError($"Failed to start the listener.\n{e.Message}");
137139

138140
}
139141

@@ -143,7 +145,7 @@ private static async Task<AuthResult> PollinationSignInAsync(bool devEnv = false
143145
UseShellExecute = true
144146
};
145147
System.Diagnostics.Process.Start(psi);
146-
LogHelper.LogInfo($"Login from {loginUrl}");
148+
Logger.Info($"Login from {loginUrl}");
147149

148150
// wait for the authorization response.
149151
var context = await listener.GetContextAsync();
@@ -153,7 +155,7 @@ private static async Task<AuthResult> PollinationSignInAsync(bool devEnv = false
153155

154156
var returnUrl = request.RawUrl.Contains("?token=") ? request.RawUrl : request.UrlReferrer?.PathAndQuery;
155157
if (string.IsNullOrEmpty(returnUrl))
156-
LogHelper.LogThrowError($"Failed to authorize the login: \n{request.RawUrl}");
158+
Logger.ThrowError($"Failed to authorize the login: \n{request.RawUrl}");
157159

158160
var auth = AuthResult.From(request.QueryString);
159161
var loggedIn = CheckGetUser(auth, out var error, devEnv);
@@ -176,7 +178,7 @@ private static async Task<AuthResult> PollinationSignInAsync(bool devEnv = false
176178
responseOutput.Flush();
177179
responseOutput.Close();
178180

179-
LogHelper.LogInfo($"Closed listener");
181+
Logger.Info($"Closed listener");
180182

181183
return auth;
182184
}
@@ -203,7 +205,7 @@ private static bool CheckGetUser(AuthResult auth, out string errorMessage, bool
203205
refreshToken: auth.RefreshToken
204206
);
205207
Helper.CurrentUser = Helper.GetUser();
206-
LogHelper.LogInfo($"Logged in as {Helper.CurrentUser.Username}");
208+
Logger.Info($"Logged in as {Helper.CurrentUser.Username}");
207209

208210
return true;
209211

@@ -212,7 +214,7 @@ private static bool CheckGetUser(AuthResult auth, out string errorMessage, bool
212214
{
213215
Configuration.Default.TokenRepo = null;
214216
Helper.CurrentUser = null;
215-
LogHelper.LogError(e);
217+
Logger.Error(e);
216218
errorMessage = e.Message;
217219
return false;
218220
//throw;

src/PollinationSDK/Helper/HandlerChecker.cs

+5-2
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
using System.Linq;
77
using System.Reflection;
88
using System.Text;
9+
using Pollination;
910

1011
namespace PollinationSDK
1112
{
@@ -15,6 +16,8 @@ namespace PollinationSDK
1516
/// </summary>
1617
public abstract class HandlerChecker
1718
{
19+
private static Microsoft.Extensions.Logging.ILogger Logger => LogUtils.GetLogger<HandlerChecker>();
20+
1821
public object CheckWithHandlers(object inputData, List<IOAliasHandler> handlers)
1922
{
2023
if (inputData == null) return inputData;
@@ -34,7 +37,7 @@ public object CheckWithHandlers(object inputData, List<IOAliasHandler> handlers)
3437
}
3538
catch (Exception e)
3639
{
37-
LogHelper.LogError(e);
40+
Logger.Error(e);
3841
errors.Add($"{e?.Message}{Environment.NewLine}From {item.Function}(Handler-{item.Language})");
3942
break;
4043
//throw;
@@ -159,7 +162,7 @@ private static Assembly LoadDll(string csProjName)
159162
}
160163
catch (Exception ex)
161164
{
162-
throw LogHelper.LogReturnError(ex, $"PollinationSDK: cannot find handler libraries.");
165+
throw Logger.ReturnError($"Cannot find handler libraries.\n{ex}");
163166
}
164167
}
165168

src/PollinationSDK/Helper/Helper.cs

+24-22
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,14 @@
1010
using System.Net;
1111
using System.Threading;
1212
using System.Threading.Tasks;
13+
using Pollination;
1314

1415
namespace PollinationSDK
1516
{
1617
public static class Helper
1718
{
18-
public static Serilog.ILogger Logger { get; set; } = Serilog.Log.Logger;
19+
private static Microsoft.Extensions.Logging.ILogger Logger => LogUtils.GetLogger(nameof(Helper));
20+
1921
public static UserPrivate CurrentUser { get; set; }
2022

2123
public static UserPrivate GetUser()
@@ -67,13 +69,13 @@ public static Project GetAProject(string userName, string projectName)
6769
// Project not found and person account, create a default demo project.
6870
if (e.ErrorCode == 404 && userName == Helper.CurrentUser.Username)
6971
{
70-
Logger.Information($"Project {projectName} is not found in account {userName}. Now creating this project.");
72+
Logger.Info($"Project {projectName} is not found in account {userName}. Now creating this project.");
7173
var ifPublic = projectName == "demo";
7274
var res = api.CreateProject(userName, new ProjectCreate(projectName, _public: ifPublic));
7375
return GetAProject(userName, projectName);
7476
}
75-
LogHelper.LogError(e, $"Failed to get the project {userName}/{projectName}");
76-
throw e;
77+
Logger.Error($"Failed to get the project {userName}/{projectName}" + "{e}", new[] { e });
78+
throw;
7779
}
7880

7981

@@ -90,14 +92,14 @@ public static Project GetWritableProject(string projectSlug)
9092

9193
public static async Task<bool> UploadDirectoryAsync(Project project, string directory, Action<int> reportProgressAction = default, CancellationToken cancellationToken = default)
9294
{
93-
LogHelper.LogInfo($"Uploading a directory {directory}");
94-
LogHelper.LogInfo($"Timeout: {Configuration.Default.Timeout}");
95+
Logger.Info($"Uploading a directory {directory}");
96+
Logger.Info($"Timeout: {Configuration.Default.Timeout}");
9597

9698
var files = Directory.GetFiles(directory, "*", SearchOption.AllDirectories);
9799
var api = new ArtifactsApi();
98100

99101
var total = files.Count();
100-
LogHelper.LogInfo($"Uploading {total} assets for project {project.Name}");
102+
Logger.Info($"Uploading {total} assets for project {project.Name}");
101103

102104
var finished = 0;
103105
var finishedPercent = 0;
@@ -125,7 +127,7 @@ public static async Task<bool> UploadDirectoryAsync(Project project, string dire
125127
finished += chunk.Count;
126128
}
127129

128-
LogHelper.LogInfo($"Finished uploading assets for project {project.Name}");
130+
Logger.Info($"Finished uploading assets for project {project.Name}");
129131

130132
// canceled by user
131133
if (cancellationToken.IsCancellationRequested) return false;
@@ -143,7 +145,7 @@ private static async Task<bool> BatchExecute(ArtifactsApi api, Project project,
143145
// canceled by user
144146
if (cancellationToken.IsCancellationRequested)
145147
{
146-
LogHelper.LogInfo($"Canceled uploading by user");
148+
Logger.Info($"Canceled uploading by user");
147149
break;
148150
}
149151

@@ -152,7 +154,7 @@ private static async Task<bool> BatchExecute(ArtifactsApi api, Project project,
152154

153155
if (finishedTask.IsFaulted || finishedTask.Exception != null)
154156
{
155-
LogHelper.LogError($"Upload exception: {finishedTask.Exception}");
157+
Logger.Error($"Upload exception: {finishedTask.Exception}");
156158
throw finishedTask.Exception;
157159
}
158160

@@ -200,18 +202,18 @@ public static async Task<bool> UploadArtifactAsync(ArtifactsApi api, Project pro
200202

201203
restRequest.AddFile("file", filePath);
202204

203-
LogHelper.LogInfo($"Started upload of {fileRelativePath}");
205+
Logger.Info($"Started upload of {fileRelativePath}");
204206
var response = await restClient.ExecuteAsync(restRequest);
205207

206208
if (response.StatusCode == HttpStatusCode.NoContent)
207209
{
208-
LogHelper.LogInfo($"Done uploading {fileRelativePath}");
210+
Logger.Info($"Done uploading {fileRelativePath}");
209211
return true;
210212
}
211213
else
212214
{
213-
LogHelper.LogInfo($"Received response code: {response.StatusCode}");
214-
LogHelper.LogInfo($"{response.Content}");
215+
Logger.Info($"Received response code: {response.StatusCode}");
216+
Logger.Info($"{response.Content}");
215217
}
216218
return false;
217219
}
@@ -533,13 +535,13 @@ public static async Task<string> DownloadArtifactAsync(ArtifactsApi api, string
533535

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

536-
LogHelper.LogInfo($"Downloading {fileRelativePath} from \n -{url}\n");
538+
Logger.Info($"Downloading {fileRelativePath} from \n -{url}\n");
537539
// get relative path correct
538540
saveAsDir = Path.GetDirectoryName(Path.Combine(saveAsDir, relativePath));
539541
saveAsDir = Path.GetFullPath(saveAsDir);
540542
var path = await Helper.DownloadUrlAsync(url.ToString(), saveAsDir, reportProgressAction, null, cancelToken);
541543

542-
LogHelper.LogInfo($"Saved {fileRelativePath} to {path}");
544+
Logger.Info($"Saved {fileRelativePath} to {path}");
543545
return path;
544546
}
545547

@@ -551,13 +553,13 @@ public static async Task<string> DownloadArtifactAsync(JobsApi api, string projO
551553

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

554-
LogHelper.LogInfo($"Downloading {fileRelativePath} from \n -{url}\n");
556+
Logger.Info($"Downloading {fileRelativePath} from \n -{url}\n");
555557
// get relative path correct
556558
saveAsDir = Path.GetDirectoryName(Path.Combine(saveAsDir, relativePath));
557559
saveAsDir = Path.GetFullPath(saveAsDir);
558560
var path = await Helper.DownloadUrlAsync(url.ToString(), saveAsDir, reportProgressAction, null, cancelToken);
559561

560-
LogHelper.LogInfo($"Saved {fileRelativePath} to {path}");
562+
Logger.Info($"Saved {fileRelativePath} to {path}");
561563
return path;
562564
}
563565

@@ -646,7 +648,7 @@ public static async Task<string> DownloadUrlAsync(string url, string saveAsDir,
646648

647649
Directory.CreateDirectory(saveAsDir);
648650
var file = Path.Combine(saveAsDir, fileName);
649-
LogHelper.LogInfo($"Downloading {url}");
651+
Logger.Info($"Downloading {url}");
650652
using (WebClient wc = new WebClient())
651653
{
652654
var prog = 0;
@@ -669,7 +671,7 @@ public static async Task<string> DownloadUrlAsync(string url, string saveAsDir,
669671
await t;
670672
if (t.IsFaulted && t.Exception != null)
671673
throw t.Exception;
672-
LogHelper.LogInfo($"Saved {fileName} to {file}");
674+
Logger.Info($"Saved {fileName} to {file}");
673675
}
674676
catch (WebException ex) when (ex.Status == WebExceptionStatus.RequestCanceled)
675677
{
@@ -689,7 +691,7 @@ public static async Task<string> DownloadUrlAsync(string url, string saveAsDir,
689691

690692
if (!File.Exists(file))
691693
{
692-
throw LogHelper.LogReturnError($"Failed to download {fileName}");
694+
throw Logger.ReturnError($"Failed to download {fileName}");
693695
}
694696
var outputDirOrFile = file;
695697

@@ -700,7 +702,7 @@ public static async Task<string> DownloadUrlAsync(string url, string saveAsDir,
700702
}
701703
catch (Exception e)
702704
{
703-
throw LogHelper.LogReturnError(e, $"Unable to unzip file {Path.GetFileName(file)}");
705+
throw Logger.ReturnError($"Unable to unzip file {Path.GetFileName(file)}\n {e}");
704706
}
705707

706708
return outputDirOrFile;

src/PollinationSDK/Helper/LogUtils.cs

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
using Microsoft.Extensions.Logging;
2+
using System;
3+
4+
namespace PollinationSDK
5+
{
6+
internal static class LogUtils
7+
{
8+
private static string _namespaceName = System.Reflection.MethodBase.GetCurrentMethod()?.DeclaringType?.Namespace ?? "Unknown Namespace";
9+
private static string _className = System.Reflection.MethodBase.GetCurrentMethod()?.DeclaringType?.Name ?? "Unknown Class";
10+
private static string _logCatagory = $"{_namespaceName}.{_className}";
11+
12+
private static Pollination.LogHelper? _helper;
13+
internal static Pollination.LogHelper Helper => _helper ??= new Pollination.LogHelper(_logCatagory);
14+
15+
internal static ILogger GetLogger<T>() => Helper.GetLogger<T>();
16+
internal static ILogger GetLogger(Type type) => Helper.GetLogger(type);
17+
internal static ILogger GetLogger(string catName) => Helper.GetLogger(catName);
18+
19+
internal static ILogger Logger => GetLogger(_logCatagory);
20+
}
21+
22+
}

0 commit comments

Comments
 (0)