Skip to content

Commit b4a47d9

Browse files
committed
[feat] SSH和SFTP的日志带上连接信息
1 parent 15462e7 commit b4a47d9

File tree

2 files changed

+36
-23
lines changed

2 files changed

+36
-23
lines changed

Services/SftpFileTransferService.cs

+15-11
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,11 @@ public class SftpFileTransferService : IFileTransferService<ConnectionInfo>
1616
private readonly Dictionary<string, IAsyncResult> _uploadAsyncResults = new();
1717

1818
private SftpClient? _client;
19-
19+
2020
private List<string>? _expectedFingerprints;
2121

2222
public ConnectionInfo? CredentialInfo { get; set; }
23-
23+
2424
public SftpFileTransferService(ILogger<SftpFileTransferService> logger, JSONNode node)
2525
{
2626
_logger = logger;
@@ -35,11 +35,11 @@ public async Task<ResultMsg> UploadFile(string path, string remotePath)
3535
if (isFile)
3636
{
3737
_logger.LogInformation(
38-
$"[{DateTime.Now}][{GetType()}.Upload] Start uploading file {Path.GetFileName(path)}({path}) to {remotePath}");
38+
$"[{DateTime.Now}][{CredentialInfo?.Host}:{CredentialInfo?.Port}({CredentialInfo?.Username})][{GetType()}.Upload] Start uploading file {Path.GetFileName(path)}({path}) to {remotePath}");
3939
if (_uploadAsyncResults.ContainsKey(remotePath))
4040
{
4141
_logger.LogWarning(
42-
$"[{DateTime.Now}][{GetType()}.Upload] File {Path.GetFileName(path)}({path}) is already uploading!");
42+
$"[{DateTime.Now}][{CredentialInfo?.Host}:{CredentialInfo?.Port}({CredentialInfo?.Username})][{GetType()}.Upload] File {Path.GetFileName(path)}({path}) is already uploading!");
4343
result.Success = false;
4444
result.Message = "Upload in progress";
4545
return result;
@@ -48,11 +48,12 @@ public async Task<ResultMsg> UploadFile(string path, string remotePath)
4848
// 默认直接覆盖远端文件
4949
FileStream input = File.OpenRead(path);
5050
result = await UploadFileAsync(input, remotePath, true);
51-
51+
5252
return result;
5353
}
5454

55-
_logger.LogError($"[{DateTime.Now}][{GetType()}.Upload] Invalid path: {path}.");
55+
_logger.LogError(
56+
$"[{DateTime.Now}][{CredentialInfo?.Host}:{CredentialInfo?.Port}({CredentialInfo?.Username})][{GetType()}.Upload] Invalid path: {path}.");
5657
result.Success = false;
5758
result.Message = "Invalid path";
5859

@@ -87,15 +88,16 @@ public async Task StartAsync(CancellationToken cancellationToken, JSONNode node)
8788
_logger.LogInformation(
8889
$"[{DateTime.Now}][{GetType()}] SHA256 fingerprint {node["expectedFingerprints"][i]} added!");
8990
}
90-
91+
9192
CredentialInfo = new ConnectionInfo(node["address"].Value, node["user"].Value,
9293
new PasswordAuthenticationMethod(node["user"].Value, node["password"].Value),
9394
new PrivateKeyAuthenticationMethod(node["user"].Value, new PrivateKeyFile(node["privateKeyPath"].Value)));
94-
95+
9596
_client = new SftpClient(CredentialInfo);
9697

9798
await _client.ConnectAsync(cancellationToken);
98-
_logger.LogInformation($"[{DateTime.Now}][{GetType()}.StartAsync] Initialized!");
99+
_logger.LogInformation(
100+
$"[{DateTime.Now}][{CredentialInfo?.Host}:{CredentialInfo?.Port}({CredentialInfo?.Username})][{GetType()}.StartAsync] Initialized!");
99101
}
100102

101103
public Task StopAsync(CancellationToken cancellationToken)
@@ -104,7 +106,8 @@ public Task StopAsync(CancellationToken cancellationToken)
104106
CancelAllDownload();
105107
_client.Disconnect();
106108
_client.Dispose();
107-
_logger.LogInformation($"[{DateTime.Now}][{GetType()}.StopAsync] Stopped!");
109+
_logger.LogInformation(
110+
$"[{DateTime.Now}][{CredentialInfo?.Host}:{CredentialInfo?.Port}({CredentialInfo?.Username})][{GetType()}.StopAsync] Stopped!");
108111
return Task.CompletedTask;
109112
}
110113

@@ -130,7 +133,8 @@ private Task<ResultMsg> UploadFileAsync(Stream input, string path, bool canOverr
130133
catch (Exception ex)
131134
{
132135
// 处理可能出现的异常
133-
_logger.LogError($"[{DateTime.Now}][{GetType()}.UploadFileAsync] ERROR! {ex}");
136+
_logger.LogError(
137+
$"[{DateTime.Now}][{CredentialInfo?.Host}:{CredentialInfo?.Port}({CredentialInfo?.Username})][{GetType()}.UploadFileAsync] ERROR! {ex}");
134138
resultMsg.Success = false;
135139
resultMsg.Message = ex.ToString();
136140
_uploadAsyncResults.Remove(path);

Services/SshCredentialService.cs

+21-12
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,8 @@ public async Task<ResultMsg> Login()
3636
{
3737
result.Success = false;
3838
result.Message = "CredentialInfo is null.";
39-
_logger.LogError($"[{DateTime.Now}][{GetType()}.Login] ERROR! {result.Message}");
39+
_logger.LogError(
40+
$"[{DateTime.Now}][{CredentialInfo?.Host}:{CredentialInfo?.Port}({CredentialInfo?.Username})][{GetType()}.Login] ERROR! {result.Message}");
4041
return result;
4142
}
4243

@@ -50,11 +51,11 @@ public async Task<ResultMsg> Login()
5051
_client.HostKeyReceived += (sender, args) =>
5152
{
5253
_logger.LogWarning(
53-
$"[{DateTime.Now}][{GetType()}.Login] Host Key received! \nHost fingerprint SHA256: {args.FingerPrintSHA256}");
54+
$"[{DateTime.Now}][{CredentialInfo?.Host}:{CredentialInfo?.Port}({CredentialInfo?.Username})][{GetType()}.Login] Host Key received! \nHost fingerprint SHA256: {args.FingerPrintSHA256}");
5455
if (_expectedFingerprints == null || _expectedFingerprints.Count <= 0)
5556
{
5657
_logger.LogError(
57-
$"[{DateTime.Now}][{GetType()}.Login] expectedFingerprints not defined! Abort the login");
58+
$"[{DateTime.Now}][{CredentialInfo?.Host}:{CredentialInfo?.Port}({CredentialInfo?.Username})][{GetType()}.Login] expectedFingerprints not defined! Abort the login");
5859
args.CanTrust = false;
5960
_client.Disconnect();
6061
result.Success = false;
@@ -67,7 +68,8 @@ public async Task<ResultMsg> Login()
6768
};
6869
_client.ErrorOccurred += (sender, args) =>
6970
{
70-
_logger.LogError($"[{DateTime.Now}][{GetType()}] SshClient ErrorOccurred! {args.Exception}");
71+
_logger.LogError(
72+
$"[{DateTime.Now}][{CredentialInfo?.Host}:{CredentialInfo?.Port}({CredentialInfo?.Username})][{GetType()}] SshClient ErrorOccurred! {args.Exception}");
7173
};
7274

7375
// 保持SSH会话
@@ -98,23 +100,27 @@ public async Task<ResultMsg> Login()
98100
// _logger.LogInformation($"[{GetType()}.Login] \"sudo su\" success!");
99101
// }
100102
}
103+
101104
result.Success = true;
102105
result.Message = string.Empty;
103106
tcs.SetResult(result);
104107
}
105108
catch (Exception ex)
106109
{
107-
_logger.LogError($"[{DateTime.Now}][{GetType()}.Login] Error when SshClient connect!\n{ex}");
110+
_logger.LogError(
111+
$"[{DateTime.Now}][{CredentialInfo?.Host}:{CredentialInfo?.Port}({CredentialInfo?.Username})][{GetType()}.Login] Error when SshClient connect!\n{ex}");
108112
result.Success = false;
109113
result.Message = $"SshClient error! {ex}";
110114
tcs.SetResult(result);
111115
}
112116

113117
var success = await tcs.Task;
114118
if (success.Success)
115-
_logger.LogInformation($"[{DateTime.Now}][{GetType()}.Login] Login success!");
119+
_logger.LogInformation(
120+
$"[{DateTime.Now}][{CredentialInfo?.Host}:{CredentialInfo?.Port}({CredentialInfo?.Username})][{GetType()}.Login] Login success!");
116121
else
117-
_logger.LogError($"[{DateTime.Now}][{GetType()}.Login] login failed! {result.Message}");
122+
_logger.LogError(
123+
$"[{DateTime.Now}][{CredentialInfo?.Host}:{CredentialInfo?.Port}({CredentialInfo?.Username})][{GetType()}.Login] login failed! {result.Message}");
118124

119125
return success;
120126
}
@@ -152,21 +158,23 @@ public async Task StartAsync(CancellationToken cancellationToken, JSONNode node)
152158
_logger.LogInformation(
153159
$"[{DateTime.Now}][{GetType()}] SHA256 fingerprint {node["expectedFingerprints"][i]} added!");
154160
}
155-
161+
156162
CredentialInfo = new ConnectionInfo(node["address"].Value, node["user"].Value,
157163
new PasswordAuthenticationMethod(node["user"].Value, node["password"].Value),
158164
new PrivateKeyAuthenticationMethod(node["user"].Value, new PrivateKeyFile(node["privateKeyPath"].Value)));
159165

160166
needSudo = node["needSudo"];
161167

162168
await Login();
163-
_logger.LogInformation($"[{DateTime.Now}][{GetType()}.StartAsync] Initialized!");
169+
_logger.LogInformation(
170+
$"[{DateTime.Now}][{CredentialInfo?.Host}:{CredentialInfo?.Port}({CredentialInfo?.Username})][{GetType()}.StartAsync] Initialized!");
164171
}
165172

166173
public async Task StopAsync(CancellationToken cancellationToken)
167174
{
168175
await Logout();
169-
_logger.LogInformation($"[{DateTime.Now}][{GetType()}.StopAsync] Stopped!");
176+
_logger.LogInformation(
177+
$"[{DateTime.Now}][{CredentialInfo?.Host}:{CredentialInfo?.Port}({CredentialInfo?.Username})][{GetType()}.StopAsync] Stopped!");
170178
}
171179

172180
public async Task<ResultMsg> RunCommand(string command)
@@ -175,7 +183,7 @@ public async Task<ResultMsg> RunCommand(string command)
175183
{
176184
command = $"sudo {command}";
177185
}
178-
186+
179187
var result = new ResultMsg();
180188
var sshCommand = _client.CreateCommand(command);
181189
try
@@ -184,7 +192,8 @@ public async Task<ResultMsg> RunCommand(string command)
184192
}
185193
catch (Exception ex)
186194
{
187-
_logger.LogError($"[{DateTime.Now}][{GetType()}] Error when executing {command}! {ex}");
195+
_logger.LogError(
196+
$"[{DateTime.Now}][{CredentialInfo?.Host}:{CredentialInfo?.Port}({CredentialInfo?.Username})][{GetType()}] Error when executing {command}! {ex}");
188197
result.Message = ex.ToString();
189198
result.Success = false;
190199
}

0 commit comments

Comments
 (0)