Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[DYN-2680] Write logs to std out instead of creating new files for each test. #10651

Merged
merged 4 commits into from
May 15, 2020
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 29 additions & 4 deletions src/DynamoCore/Logging/DynamoLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
using Dynamo.Configuration;
using Dynamo.Core;
using Dynamo.Exceptions;
using Dynamo.Interfaces;

namespace Dynamo.Logging
{
Expand Down Expand Up @@ -75,6 +74,7 @@ public class DynamoLogger: NotificationObject, ILogger, IDisposable
private string _warning;
private WarningLevel _warningLevel;
private bool _isDisposed;
private bool testMode;

private TextWriter FileWriter { get; set; }
private StringBuilder ConsoleWriter { get; set; }
Expand Down Expand Up @@ -157,7 +157,20 @@ public IEnumerable<NotificationMessage> StartupNotifications
/// </summary>
/// <param name="debugSettings">Debug settings</param>
/// <param name="logDirectory">Directory path where log file will be written</param>
public DynamoLogger(DebugSettings debugSettings, string logDirectory)
[Obsolete("This will be removed in 3.0, please use DynamoLogger(debugSettings, logDirectory, isTestMode) instead.")]
public DynamoLogger(DebugSettings debugSettings, string logDirectory) : this(debugSettings, logDirectory, false)
{

}

/// <summary>
/// Initializes a new instance of <see cref="DynamoLogger"/> class
/// with specified debug settings and directory where to write logs
/// </summary>
/// <param name="debugSettings">Debug settings</param>
/// <param name="logDirectory">Directory path where log file will be written</param>
/// <param name="isTestMode">Test mode is true or false.</param>
public DynamoLogger(DebugSettings debugSettings, string logDirectory, Boolean isTestMode)
{
lock (guardMutex)
{
Expand All @@ -169,7 +182,12 @@ public DynamoLogger(DebugSettings debugSettings, string logDirectory)

notifications = new List<NotificationMessage>();

StartLogging(logDirectory);
testMode = isTestMode;

if (!testMode)
{
StartLoggingToConsoleAndFile(logDirectory);
}
}
}

Expand Down Expand Up @@ -197,6 +215,13 @@ private void Log(string message, LogLevel level, bool reportModification)
if (debugSettings.VerboseLogging)
Analytics.LogPiiInfo("LogMessage-" + level.ToString(), message);

// In test mode, write the logs only to std out.
if (testMode)
{
Console.WriteLine(string.Format("{0} : {1}", DateTime.UtcNow.ToString("u"), message));
return;
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not just leverage on the existing code for the console logging by setting the level variable to LogLevel.Console if testMode is true?

Copy link
Contributor Author

@reddyashish reddyashish May 13, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The LogLevel.Console is configured to write to both the dynamo console and to the log file. So couldn't use it.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are indeed right. The fact that it does both things having that name is confusing :)


switch (level)
{
//write to the console
Expand Down Expand Up @@ -377,7 +402,7 @@ internal void ClearLog()
/// <summary>
/// Begin logging.
/// </summary>
private void StartLogging(string logDirectory)
private void StartLoggingToConsoleAndFile(string logDirectory)
{
lock (this.guardMutex)
{
Expand Down
2 changes: 1 addition & 1 deletion src/DynamoCore/Models/DynamoModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -570,7 +570,7 @@ protected DynamoModel(IStartConfiguration config)
IsHeadless = config.IsHeadless;

DebugSettings = new DebugSettings();
Logger = new DynamoLogger(DebugSettings, pathManager.LogDirectory);
Logger = new DynamoLogger(DebugSettings, pathManager.LogDirectory, IsTestMode);

foreach (var exception in exceptions)
{
Expand Down
14 changes: 11 additions & 3 deletions test/DynamoCoreTests/CoreTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
using Dynamo.Graph.Workspaces;
using Dynamo.Models;
using Dynamo.Selection;
using Dynamo.Tests.Loggings;
using NUnit.Framework;
using DynCmd = Dynamo.Models.DynamoModel;

Expand Down Expand Up @@ -235,10 +236,17 @@ public void CanAddToSelectionCommand()
[Category("UnitTests")]
public void CanClearLog()
{
Assert.AreNotEqual(0, CurrentDynamoModel.Logger.LogText.Length);
// Get the dynamo logger in non-test mode, as we write the logs
// to dynamo console and to a file only in non-test mode.

CurrentDynamoModel.Logger.ClearLog();
Assert.AreEqual(0, CurrentDynamoModel.Logger.LogText.Length);
DynamoLoggerTest dynamoLoggerTest = new DynamoLoggerTest();
var logger = dynamoLoggerTest.GetDynamoLoggerWithTestModeFalse();

Assert.AreNotEqual(0, logger.LogText.Length);

logger.ClearLog();

Assert.AreEqual(0, logger.LogText.Length);
}

// Clearworkspace
Expand Down
60 changes: 30 additions & 30 deletions test/DynamoCoreTests/Logging/DynamoLoggerTest.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,9 @@
using Dynamo.Logging;
using Dynamo.Updates;
using Moq;
using NUnit.Framework;
using DynUpdateManager = Dynamo.Updates.UpdateManager;
using System;
using System.Collections.Generic;
using Dynamo.Configuration;
using Dynamo.Core;
using System.Collections.Generic;
using System;
using Dynamo.Interfaces;
using Dynamo.Logging;
using NUnit.Framework;

namespace Dynamo.Tests.Loggings
{
Expand All @@ -17,6 +13,28 @@ class DynamoLoggerTest : DynamoModelTestBase
private const string DOWNLOAD_SOURCE_PATH_S = "http://downloadsourcepath/";
private const string SIGNATURE_SOURCE_PATH_S = "http://SignatureSourcePath/";
private PathManager pathManager;
internal DynamoLogger logger;

// Returns the dynamo logger object in non-test mode.
internal DynamoLogger GetDynamoLoggerWithTestModeFalse()
{
pathManager = new PathManager(new PathManagerParams{ });

// Ensure we have all directories in place.
var exceptions = new List<Exception>();
pathManager.EnsureDirectoryExistence(exceptions);

//By setting the VerboseLogging we will enable a piece of code inside the method::
//private void Log(string message, LogLevel level, bool reportModification)
var debugSettings = new DebugSettings
{
VerboseLogging = true
};

var logger = new DynamoLogger(debugSettings, pathManager.LogDirectory, false);

return logger;
}

/// <summary>
/// This test method will check the LogEventArgs.LogEventArgs
Expand Down Expand Up @@ -45,27 +63,9 @@ public void test_dynamologger_LogEventArgs()
[Category("UnitTests")]
public void test_dynamologger_logger()
{
//Arrange
//This has been done in the base class but we need to do it again because the pathManager is private
var config = CreateStartConfiguration(dynamoSettings);
pathManager = new PathManager(new PathManagerParams
{
CorePath = config.DynamoCorePath,
HostPath = config.DynamoHostPath,
PathResolver = config.PathResolver
});
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just to confirm, these params were not needed, right?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah, these were null values.


// Ensure we have all directories in place.
var exceptions = new List<Exception>();
pathManager.EnsureDirectoryExistence(exceptions);

//By setting the VerboseLogging we will enable a piece of code inside the method::
//private void Log(string message, LogLevel level, bool reportModification)
var debugSettings = new DebugSettings
{
VerboseLogging = true
};
var logger = new DynamoLogger(debugSettings, pathManager.LogDirectory);
// Get the dynamo logger in non-test mode, as we write the logs
// to dynamo console and to a file only in non-test mode.
logger = GetDynamoLoggerWithTestModeFalse();

//Act
logger.LogWarning("Testing Logging Warning", WarningLevel.Error);
Expand All @@ -77,7 +77,7 @@ public void test_dynamologger_logger()
logger.LogError("Testing Logging Error","Error Details");

//Assert
//Check if the logged info was inserted inside the logged text (the log file cannot be opened due that is being used by the base class)
//Check if the logged info is stored in the LogText property (the log file cannot be opened due that is being used by the base class)
Assert.IsTrue(logger.LogText.Contains("Testing Logging Warning"));

logger.Dispose();
Expand Down
31 changes: 21 additions & 10 deletions test/DynamoCoreTests/Migration/WorkspaceMigrationsTests.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
using Dynamo.Migration;
using NUnit.Framework;
using System;
using System.IO;
using System.Xml;
using Dynamo.Migration;
using NUnit.Framework;

namespace Dynamo.Tests.Migrations
{
Expand All @@ -15,21 +16,31 @@ class WorkspaceMigrationsTests : DynamoModelTestBase
[Category("UnitTests")]
public void TestWorkspaceMigrations()
{
string consoleOutput;

//Arrange
string openPath = Path.Combine(TestDirectory, @"core\NodeStates.dyn");
RunModel(openPath);
string logFileText = string.Empty;
XmlDocument xmlDoc = new XmlDocument();

//Act
//Create a instance of WorkspaceMigration and call the function that writes to the log
var workMigration = new WorkspaceMigrations(CurrentDynamoModel);
workMigration.Migrate_0_5_3_to_0_6_0(xmlDoc);
var currentLoggerPath = CurrentDynamoModel.Logger.LogPath;
using (StringWriter stringWriter = new StringWriter())
{
Console.SetOut(stringWriter);

//Act
//Create a instance of WorkspaceMigration and call the function that writes to the log
var workMigration = new WorkspaceMigrations(CurrentDynamoModel);
workMigration.Migrate_0_5_3_to_0_6_0(xmlDoc);

consoleOutput = stringWriter.ToString();

StreamWriter sw = new StreamWriter(Console.OpenStandardOutput());
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should you call dispose on StreamWriter? I believe it implements IDisposable!

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sorry, looked too quickly, didn't see this was one test, not the logger!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can avoid creating the StreamWriter object. Saving the std out beforehand and setting it back.

Console.SetOut(sw);
}

//Assert
Assert.IsTrue(File.Exists(currentLoggerPath));//Check that the log was created successfully
Assert.IsTrue(CurrentDynamoModel.Logger.LogText.Contains("migration from 0.5.3.x to 0.6.1.x"));//Checks that the log text contains the migration info
//Checks that the console output text contains the migration info
Assert.IsTrue(consoleOutput.Contains("migration from 0.5.3.x to 0.6.1.x"));
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe for this test we actually want to use the non-test version of the logger? I'm thinking that having a persistent log after a migration is done is desired and should be tested to exist.

Copy link
Contributor Author

@reddyashish reddyashish May 14, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The thing is, the dynamo logger is created from the dynamo model when the dynamo model is initialized from the tests. It is a read only property and we cannot create an instance of logger in non test mode here, then add it to the model(only then this log message will be written to a file).

}
}
}