// Copyright Keysight Technologies 2012-2019
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, you can obtain one at http://mozilla.org/MPL/2.0/.
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
namespace OpenTap
{
///
/// Listens to events in the log and outputs them to a file. Can be configured with filters on the log verbosity level.
/// FilePath supports replacement of date and verdict.
///
[Display("Text Log", Group:"Text", Description: "Save the log from a test plan run as a text file.")]
public class LogResultListener : ResultListener, IFileResultStore
{
/// File path of log file.
[FilePath(FilePathAttribute.BehaviorChoice.Save, "txt")]
[HelpLink(@"EditorHelp.chm::/Configurations/Using Tags and Variables in File Names.html")]
[Display("File Path", Description: "Output file path for the log file.")]
public MacroString FilePath { get; set; }
string IFileResultStore.FilePath
{
get => FilePath.Expand();
set => FilePath.Text = value;
}
/// FilterOptions for filtering on log message verbosity level.
[Flags]
public enum FilterOptionsType
{
/// Debug messages.
[Display("Debug", "Include debug level log messages.")]
Verbose = 1,
/// Information messages.
[Display("Information", "Include information level log messages.")]
Info = 2,
/// Warning messages.
[Display("Warning", "Include warning level log messages.")]
Warnings = 4,
/// Error messages.
[Display("Error", "Include error level log messages.")]
Errors = 8
}
/// To string converter LUT for filter options.
readonly Dictionary logFilterOptionsLUT = new Dictionary
{
{FilterOptionsType.Verbose, "Debug"},
{FilterOptionsType.Info, "Information"},
{FilterOptionsType.Warnings, "Warning"},
{FilterOptionsType.Errors, "Error"}
};
/// Contains the FilterOptions flags. Any combination of the four flags is allowed.
[Display("Filter Options", Description: "Select how to filter the log messages if needed.")]
public FilterOptionsType FilterOptions { get; set; }
bool UseFilter()
{
return FilterOptions != (FilterOptionsType.Verbose |
FilterOptionsType.Warnings |
FilterOptionsType.Info |
FilterOptionsType.Errors);
}
/// Sets default values.
public LogResultListener()
{
Name = "Log";
FilePath = new MacroString { Text = "Results/-.txt" };
FilterOptions = FilterOptionsType.Verbose |
FilterOptionsType.Warnings |
FilterOptionsType.Info |
FilterOptionsType.Errors;
}
void FilterCopyStream(Stream input, Stream outStream)
{
using StreamWriter streamWriter = new StreamWriter(outStream, System.Text.Encoding.UTF8, bufferSize: 4 * 1024, leaveOpen: true);
using StreamReader streamReader = new StreamReader(input);
Regex rx = new Regex("^(?