Skip to content

Commit d7f60c2

Browse files
authored
Merge pull request #5625 from Azure/fix-logs
Fixing broken logging
2 parents 0238064 + c6bff83 commit d7f60c2

File tree

3 files changed

+59
-11
lines changed

3 files changed

+59
-11
lines changed

src/WebJobs.Script.WebHost/Management/FunctionsSyncManager.cs

Lines changed: 28 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -38,13 +38,15 @@ public sealed class FunctionsSyncManager : IFunctionsSyncManager, IDisposable
3838
private readonly bool _ownsHttpClient;
3939
private readonly ScriptSettingsManager _settings;
4040
private readonly SemaphoreSlim _syncSemaphore = new SemaphoreSlim(1, 1);
41+
private readonly TraceWriter _traceWriter;
4142

4243
private CloudBlockBlob _hashBlob;
4344

4445
public FunctionsSyncManager(ScriptHostConfiguration hostConfig, ILoggerFactory loggerFactory, ISecretManager secretManager, ScriptSettingsManager settings, HttpClient httpClient = null)
4546
{
4647
_hostConfig = hostConfig;
47-
_logger = loggerFactory.CreateLogger(ScriptConstants.LogCategoryHostGeneral);
48+
_logger = loggerFactory.CreateLogger<FunctionsSyncManager>();
49+
_traceWriter = hostConfig.TraceWriter.WithDefaults(typeof(FunctionsSyncManager).FullName);
4850
_secretManager = secretManager;
4951
_settings = settings;
5052

@@ -76,6 +78,7 @@ public async Task<SyncTriggersResult> TrySyncTriggersAsync(bool checkHash = fals
7678
result.Success = false;
7779
result.Error = "Invalid environment for SyncTriggers operation.";
7880
_logger.LogWarning(result.Error);
81+
_traceWriter.Warning(result.Error);
7982
return result;
8083
}
8184

@@ -119,6 +122,7 @@ public async Task<SyncTriggersResult> TrySyncTriggersAsync(bool checkHash = fals
119122
result.Success = false;
120123
result.Error = "SyncTriggers operation failed.";
121124
_logger.LogError(0, ex, result.Error);
125+
_traceWriter.Error(result.Error, ex);
122126
}
123127
finally
124128
{
@@ -171,7 +175,9 @@ internal async Task<string> CheckHashAsync(CloudBlockBlob hashBlob, string conte
171175
if (await hashBlob.ExistsAsync())
172176
{
173177
lastHash = await hashBlob.DownloadTextAsync();
174-
_logger.LogDebug($"SyncTriggers hash (Last='{lastHash}', Current='{currentHash}')");
178+
string message = $"SyncTriggers hash (Last='{lastHash}', Current='{currentHash}')";
179+
_logger.LogDebug(message);
180+
_traceWriter.Verbose(message);
175181
}
176182

177183
if (string.Compare(currentHash, lastHash) != 0)
@@ -184,7 +190,9 @@ internal async Task<string> CheckHashAsync(CloudBlockBlob hashBlob, string conte
184190
catch (Exception ex)
185191
{
186192
// best effort
187-
_logger.LogError(0, ex, "Error checking SyncTriggers hash");
193+
string error = "Error checking SyncTriggers hash";
194+
_logger.LogError(0, ex, error);
195+
_traceWriter.Error(error, ex);
188196
}
189197

190198
// if the last and current hash values are the same,
@@ -199,12 +207,16 @@ internal async Task UpdateHashAsync(CloudBlockBlob hashBlob, string hash)
199207
// hash value has changed or was not yet stored
200208
// update the last hash value in storage
201209
await hashBlob.UploadTextAsync(hash);
202-
_logger.LogDebug($"SyncTriggers hash updated to '{hash}'");
210+
string message = $"SyncTriggers hash updated to '{hash}'";
211+
_logger.LogDebug(message);
212+
_traceWriter.Verbose(message);
203213
}
204214
catch (Exception ex)
205215
{
206216
// best effort
207-
_logger.LogError(0, ex, "Error updating SyncTriggers hash");
217+
string error = "Error updating SyncTriggers hash";
218+
_logger.LogError(0, ex, error);
219+
_traceWriter.Error(error, ex);
208220
}
209221
}
210222

@@ -298,7 +310,9 @@ public async Task<string> GetSyncTriggersPayload()
298310
// The settriggers call to the FE enforces a max request size
299311
// limit. If we're over limit, revert to the minimal triggers
300312
// format.
301-
_logger.LogWarning($"SyncTriggers payload of length '{json.Length}' exceeds max length of '{ScriptConstants.MaxTriggersStringLength}'. Reverting to minimal format.");
313+
string warning = $"SyncTriggers payload of length '{json.Length}' exceeds max length of '{ScriptConstants.MaxTriggersStringLength}'. Reverting to minimal format.";
314+
_logger.LogWarning(warning);
315+
_traceWriter.Warning(warning);
302316
return JsonConvert.SerializeObject(triggersArray);
303317
}
304318

@@ -428,18 +442,23 @@ internal static HttpRequestMessage BuildSetTriggersRequest()
428442
request.Headers.Add("x-ms-site-restricted-token", token);
429443
request.Content = new StringContent(content, Encoding.UTF8, "application/json");
430444

431-
_logger.LogDebug($"Making SyncTriggers request (RequestId={requestId}, Uri={request.RequestUri.ToString()}, Content={sanitizedContentString}).");
445+
string message = $"Making SyncTriggers request (RequestId={requestId}, Uri={request.RequestUri.ToString()}, Content={sanitizedContentString}).";
446+
_logger.LogDebug(message);
447+
_traceWriter.Verbose(message);
432448

433449
var response = await _httpClient.SendAsync(request);
434450
if (response.IsSuccessStatusCode)
435451
{
436-
_logger.LogDebug($"SyncTriggers call succeeded.");
452+
message = $"SyncTriggers call succeeded.";
453+
_logger.LogDebug(message);
454+
_traceWriter.Verbose(message);
437455
return (true, null);
438456
}
439457
else
440458
{
441-
string message = $"SyncTriggers call failed (StatusCode={response.StatusCode}).";
459+
message = $"SyncTriggers call failed (StatusCode={response.StatusCode}).";
442460
_logger.LogDebug(message);
461+
_traceWriter.Verbose(message);
443462
return (false, message);
444463
}
445464
}

src/WebJobs.Script/ScriptConstants.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,6 @@ public static class ScriptConstants
108108
/// This constant is also defined in Antares, where the limit is ultimately enforced
109109
/// for settriggers calls. If we raise that limit there, we should raise here as well.
110110
/// </summary>
111-
public const int MaxTriggersStringLength = 102400;
111+
public const int MaxTriggersStringLength = 204800;
112112
}
113113
}

test/WebJobs.Script.Tests/Management/FunctionsSyncManagerTests.cs

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
using System;
55
using System.Collections.Generic;
6+
using System.Diagnostics;
67
using System.IO;
78
using System.IO.Abstractions;
89
using System.Linq;
@@ -29,6 +30,7 @@ public class FunctionsSyncManagerTests : IDisposable
2930
private readonly string _testRootScriptPath;
3031
private readonly string _testHostConfigFilePath;
3132
private readonly ScriptHostConfiguration _hostConfig;
33+
private readonly TestTraceWriter _traceWriter;
3234
private readonly FunctionsSyncManager _functionsSyncManager;
3335
private readonly Dictionary<string, string> _vars;
3436
private readonly StringBuilder _contentBuilder;
@@ -40,6 +42,7 @@ public class FunctionsSyncManagerTests : IDisposable
4042

4143
public FunctionsSyncManagerTests()
4244
{
45+
_traceWriter = new TestTraceWriter(TraceLevel.Verbose);
4346
_testRootScriptPath = Path.GetTempPath();
4447
_testHostConfigFilePath = Path.Combine(_testRootScriptPath, ScriptConstants.HostMetadataFileName);
4548
FileUtility.DeleteFileSafe(_testHostConfigFilePath);
@@ -49,7 +52,8 @@ public FunctionsSyncManagerTests()
4952
RootScriptPath = @"x:\root\site\wwwroot",
5053
IsSelfHost = false,
5154
RootLogPath = @"x:\root\LogFiles\Application\Functions",
52-
TestDataPath = @"x:\root\data\functions\sampledata"
55+
TestDataPath = @"x:\root\data\functions\sampledata",
56+
TraceWriter = _traceWriter
5357
};
5458
_hostConfig.HostConfig.HostId = "testhostid123";
5559

@@ -438,6 +442,31 @@ public void Use_Website_Name_If_Website_Hostname_Is_Not_Available(string envKey,
438442
}
439443
}
440444

445+
[Fact]
446+
public async Task Logging_ConfiguredCorrectly()
447+
{
448+
_scriptSettingsManagerMock.Setup(p => p.GetSetting(EnvironmentSettingNames.AzureWebsiteArmCacheEnabled)).Returns("1");
449+
450+
using (var env = new TestScopedEnvironmentVariable(_vars))
451+
{
452+
var syncResult = await _functionsSyncManager.TrySyncTriggersAsync();
453+
Assert.True(syncResult.Success, "SyncTriggers should return success true");
454+
455+
var logs = _loggerProvider.GetAllLogMessages();
456+
var log = logs.First();
457+
int startIdx = log.FormattedMessage.IndexOf("Content=") + 8;
458+
int endIdx = log.FormattedMessage.LastIndexOf(')');
459+
var triggersLog = log.FormattedMessage.Substring(startIdx, endIdx - startIdx).Trim();
460+
var logObject = JObject.Parse(triggersLog);
461+
462+
// just verifying here that we're logging to both loggers, to ensure
463+
// we're writing system logs
464+
var trace = _traceWriter.GetTraces().First();
465+
Assert.Equal(log.FormattedMessage, trace.Message);
466+
Assert.Equal(log.Category, trace.Source);
467+
}
468+
}
469+
441470
private static HttpClient CreateHttpClient(MockHttpHandler httpHandler)
442471
{
443472
return new HttpClient(httpHandler);

0 commit comments

Comments
 (0)