Aracılığıyla paylaş


TaskLoggingHelper Class

Definition

Helper logging class - contains all the logging methods used by tasks. A TaskLoggingHelper object is passed to every task by MSBuild. For tasks that derive from the Task class, it is provided in the Log property. This class is thread safe: tasks can log from any threads.

public ref class TaskLoggingHelper : MarshalByRefObject
public ref class TaskLoggingHelper
public class TaskLoggingHelper : MarshalByRefObject
public class TaskLoggingHelper
type TaskLoggingHelper = class
    inherit MarshalByRefObject
type TaskLoggingHelper = class
Public Class TaskLoggingHelper
Inherits MarshalByRefObject
Public Class TaskLoggingHelper
Inheritance
TaskLoggingHelper
Inheritance
TaskLoggingHelper
Derived

Examples

The following example shows the code for a task that creates one or more directories.

using System;
using System.IO;
using System.Security;
using System.Collections;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;

namespace Microsoft.Build.Tasks
{
    /*
     * Class: MakeDir
     *
     * An MSBuild task that creates one or more directories.
     *
     */
    public class MakeDir : Task
    {
        // The Required attribute indicates the following to MSBuild:
        //	     - if the parameter is a scalar type, and it is not supplied, fail the build immediately
        //	     - if the parameter is an array type, and it is not supplied, pass in an empty array
        // In this case the parameter is an array type, so if a project fails to pass in a value for the
            // Directories parameter, the task will get invoked, but this implementation will do nothing,
            // because the array will be empty.
        [Required]
            // Directories to create.
        public ITaskItem[] Directories
        {
            get
            {
                return directories;
            }

            set
            {
                directories = value;
            }
        }

        // The Output attribute indicates to MSBuild that the value of this property can be gathered after the
        // task has returned from Execute(), if the project has an <Output> tag under this task's element for
        // this property.
        [Output]
        // A project may need the subset of the inputs that were actually created, so make that available here.
        public ITaskItem[] DirectoriesCreated
        {
            get
            {
                return directoriesCreated;
            }
        }

        private ITaskItem[] directories;
        private ITaskItem[] directoriesCreated;

        /// <summary>
        /// Execute is part of the Microsoft.Build.Framework.ITask interface.
        /// When it's called, any input parameters have already been set on the task's properties.
        /// It returns true or false to indicate success or failure.
        /// </summary>
        public override bool Execute()
        {
            ArrayList items = new ArrayList();
            foreach (ITaskItem directory in Directories)
            {
                // ItemSpec holds the filename or path of an Item
                if (directory.ItemSpec.Length > 0)
                {
                    try
                    {
                        // Only log a message if we actually need to create the folder
                        if (!Directory.Exists(directory.ItemSpec))
                        {
                            Log.LogMessage(MessageImportance.Normal, "Creating directory " + directory.ItemSpec);
                            Directory.CreateDirectory(directory.ItemSpec);
                        }

                        // Add to the list of created directories
                        items.Add(directory);
                    }
                    // If a directory fails to get created, log an error, but proceed with the remaining
                    // directories.
                    catch (Exception ex)
                    {
                        if (ex is IOException
                            || ex is UnauthorizedAccessException
                            || ex is PathTooLongException
                            || ex is DirectoryNotFoundException
                            || ex is SecurityException)
                        {
                            Log.LogError("Error trying to create directory " + directory.ItemSpec + ". " + ex.Message);
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
            }

            // Populate the "DirectoriesCreated" output items.
            directoriesCreated = (ITaskItem[])items.ToArray(typeof(ITaskItem));

            // Log.HasLoggedErrors is true if the task logged any errors -- even if they were logged
            // from a task's constructor or property setter. As long as this task is written to always log an error
            // when it fails, we can reliably return HasLoggedErrors.
            return !Log.HasLoggedErrors;
        }
    }
}

Constructors

TaskLoggingHelper(IBuildEngine, String)

Public constructor which can be used by task factories to assist them in logging messages.

TaskLoggingHelper(ITask)

public constructor

Properties

BuildEngine

Shortcut property for getting our build engine - we retrieve it from the task instance

HasLoggedErrors

Has the task logged any errors through this logging helper object?

HelpKeywordPrefix

Gets or sets the prefix used to compose help keywords from string resource names.

IsTaskInputLoggingEnabled

Returns true if the build is configured to log all task inputs.

TaskName

Gets the name of the parent task.

TaskResources

Used to load culture-specific resources. Derived classes should register their resources either during construction, or via this property, if they have localized strings.

Methods

ExtractMessageCode(String, String)

Extracts the message code (if any) prefixed to the given message string. Message code prefixes must match the following .NET regular expression in order to be recognized: ^\s*[A-Za-z]+\d+:\s* Thread safe.

FormatResourceString(String, Object[])

Loads the specified resource string and optionally formats it using the given arguments. The current thread's culture is used for formatting.

Requires the owner task to have registered its resources either via the Task (or TaskMarshalByRef) base class constructor, or the Task.TaskResources (or AppDomainIsolatedTask.TaskResources) property.

Thread safe.

FormatString(String, Object[])

Formats the given string using the variable arguments passed in. The current thread's culture is used for formatting. Thread safe.

GetInnerExceptionMessageString(Exception)

Flatten the inner exception message

GetResourceMessage(String)

Get the message from resource in task library. Thread safe.

InitializeLifetimeService()

InitializeLifetimeService is called when the remote object is activated. This method will determine how long the lifetime for the object will be. Thread safe. However, InitializeLifetimeService and MarkAsInactive should only be called in that order, together or not at all, and no more than once.

LogCommandLine(MessageImportance, String)

Logs the command line for a task's underlying tool/executable/shell command, using the given importance level. Thread safe.

LogCommandLine(String)

Logs the command line for a task's underlying tool/executable/shell command. Thread safe.

LogCriticalMessage(String, String, String, String, Int32, Int32, Int32, Int32, String, Object[])

Logs a critical message using the specified string and other message details. Thread safe.

LogError(String, Object[])

Logs an error using the specified string. Thread safe.

LogError(String, String, String, String, Int32, Int32, Int32, Int32, String, Object[])

Logs an error using the specified string and other error details. Thread safe.

LogError(String, String, String, String, String, Int32, Int32, Int32, Int32, String, Object[])

Logs an error using the specified string and other error details. Thread safe.

LogErrorFromException(Exception, Boolean, Boolean, String)

Logs an error using the message, and optionally the stack-trace from the given exception, and optionally inner exceptions too. Thread safe.

LogErrorFromException(Exception, Boolean)

Logs an error using the message (and optionally the stack-trace) from the given exception context. Thread safe.

LogErrorFromException(Exception)

Logs an error using the message from the given exception context. No callstack will be shown. Thread safe.

LogErrorFromResources(String, Object[])

Logs an error using the specified resource string. Thread safe.

LogErrorFromResources(String, String, String, String, Int32, Int32, Int32, Int32, String, Object[])

Logs an error using the specified resource string and other error details. Thread safe.

LogErrorWithCodeFromResources(String, Object[])

Logs an error using the specified resource string. If the message has an error code prefixed to it, the code is extracted and logged with the message. If a help keyword prefix has been provided, a help keyword for the host IDE is also logged with the message. The help keyword is composed by appending the string resource name to the prefix.

A task can provide a help keyword prefix either via the Task (or TaskMarshalByRef) base class constructor, or the Task.HelpKeywordPrefix (or AppDomainIsolatedTask.HelpKeywordPrefix) property.

Thread safe.

LogErrorWithCodeFromResources(String, String, Int32, Int32, Int32, Int32, String, Object[])

Logs an error using the specified resource string and other error details. If the message has an error code prefixed, the code is extracted and logged with the message. If a help keyword prefix has been provided, a help keyword for the host IDE is also logged with the message. The help keyword is composed by appending the error message resource string name to the prefix.

A task can provide a help keyword prefix either via the Task (or TaskMarshalByRef) base class constructor, or the Task.HelpKeywordPrefix (or AppDomainIsolatedTask.HelpKeywordPrefix) property.

Thread safe.

LogExternalProjectFinished(String, String, String, Boolean)

Small helper for logging the custom ExternalProjectFinished build event. Thread safe.

LogExternalProjectStarted(String, String, String, String)

Small helper for logging the custom ExternalProjectStarted build event Thread safe.

LogIncludeGeneratedFile(String, String)

Logs a file generated from the given data.

LogMessage(MessageImportance, String, Object[])

Logs a message of the given importance using the specified string. Thread safe.

LogMessage(String, Object[])

Logs a message using the specified string. Thread safe.

LogMessage(String, String, String, String, Int32, Int32, Int32, Int32, MessageImportance, String, Object[])

Logs a message using the specified string and other message details. Thread safe.

LogMessageFromResources(MessageImportance, String, Object[])

Logs a message of the given importance using the specified resource string. Thread safe.

LogMessageFromResources(String, Object[])

Logs a message using the specified resource string. Thread safe.

LogMessageFromText(String, MessageImportance)

Logs an error/warning/message from the given line of text. Errors/warnings are only logged for lines that fit a particular (canonical) format -- all other lines are treated as messages. Thread safe.

LogMessagesFromFile(String, MessageImportance)

Logs errors/warnings/messages for each line of text in the given file. Errors/warnings are only logged for lines that fit a particular (canonical) format -- the remaining lines are treated as messages. Thread safe.

LogMessagesFromFile(String)

Logs errors/warnings/messages for each line of text in the given file. Errors/warnings are only logged for lines that fit a particular (canonical) format -- the remaining lines are treated as messages. Thread safe.

LogMessagesFromStream(TextReader, MessageImportance)

Logs errors/warnings/messages for each line of text in the given stream. Errors/warnings are only logged for lines that fit a particular (canonical) format -- the remaining lines are treated as messages. Thread safe.

LogsMessagesOfImportance(MessageImportance)

Returns true if a message of given importance should be logged because it is possible that a logger consuming it exists.

LogTelemetry(String, IDictionary<String,String>)

Logs telemetry with the specified event name and properties.

LogWarning(String, Object[])

Logs a warning using the specified string. Thread safe.

LogWarning(String, String, String, String, Int32, Int32, Int32, Int32, String, Object[])

Logs a warning using the specified string and other warning details. Thread safe.

LogWarning(String, String, String, String, String, Int32, Int32, Int32, Int32, String, Object[])

Logs a warning using the specified string and other warning details. Thread safe.

LogWarningFromException(Exception, Boolean)

Logs a warning using the message (and optionally the stack-trace) from the given exception context. Thread safe.

LogWarningFromException(Exception)

Logs a warning using the message from the given exception context. Thread safe.

LogWarningFromResources(String, Object[])

Logs a warning using the specified resource string. Thread safe.

LogWarningFromResources(String, String, String, String, Int32, Int32, Int32, Int32, String, Object[])

Logs a warning using the specified resource string and other warning details. Thread safe.

LogWarningWithCodeFromResources(String, Object[])

Logs a warning using the specified resource string. If the message has a warning code prefixed to it, the code is extracted and logged with the message. If a help keyword prefix has been provided, a help keyword for the host IDE is also logged with the message. The help keyword is composed by appending the string resource name to the prefix.

A task can provide a help keyword prefix either via the Task (or TaskMarshalByRef) base class constructor, or the Task.HelpKeywordPrefix (or AppDomainIsolatedTask.HelpKeywordPrefix) property.

Thread safe.

LogWarningWithCodeFromResources(String, String, Int32, Int32, Int32, Int32, String, Object[])

Logs a warning using the specified resource string and other warning details. If the message has a warning code, the code is extracted and logged with the message. If a help keyword prefix has been provided, a help keyword for the host IDE is also logged with the message. The help keyword is composed by appending the warning message resource string name to the prefix.

A task can provide a help keyword prefix either via the Task (or TaskMarshalByRef) base class constructor, or the Task.HelpKeywordPrefix (or AppDomainIsolatedTask.HelpKeywordPrefix) property.

Thread safe.

MarkAsInactive()

Notifies this object that its work is done. Thread safe. However, InitializeLifetimeService and MarkAsInactive should only be called in that order, together or not at all, and no more than once.

Applies to