officescripts-logging-framework
    Preparing search index...

    Class ExcelAppender

    Singleton appender that logs messages to a specified Excel cell. Logs messages in color based on the LOG_EVENT enum:

    • ERROR: red, WARN: orange, INFO: green, TRACE: gray
    • Such colors can be customized by the user

    Usage:

    • Must call ExcelAppender.getInstance(ExcelScript.Range) once with a valid single cell range.
    • The range is used to display log messages.
    const range = workbook.getActiveWorksheet().getRange("A1")
    const appender = ExcelAppender.getInstance(range)
    appender.log("This is an info message", LOG_EVENT.INFO) // Log an info message
    // Better use:
    const logger = LoggerImpl.getInstance(LoggerImpl.LOG_LEVEL.INFO)
    logger.addAppender(appender) // Add the Excel appender to the logger
    logger.info("This is an info message")
    • The appender requires a single cell range to display log messages.
    • The colors for each log event type can be customized by passing a map of LOG_EVENT types to hex color strings.
    • The appender clears the cell content if it is not empty before writing a new log message.
    • The appender uses the ExcelScript.Range API to write messages, so it is designed to work in Office Scripts.
    • The appender is a singleton, so it should not be instantiated multiple times.
    • The appender uses a private constructor to prevent user instantiation, and the instance is created via the static getInstance method.
    • The appender validates the input range and colors when creating the instance.
    • LOG_EVENT for the log event types used to determine the color of the message.
    • LogEvent for the structure of log events.
    • Appender for the interface definition.
    • AbstractAppender for the base class documentation.
    • Layout for the layout used to format log events before sending them to Excel.
    • ConsoleAppender Another implementation of the Appender interface that logs messages to the console.

    Hierarchy (View Summary)

    Implements

    Index

    Properties

    DEFAULT_EVENT_FONTS: Readonly<
        { "1": "9c0006"; "2": "ed7d31"; "3": "548235"; "4": "7f7f7f" },
    > = ...

    Default colors for log events, used if no custom colors are provided. The colors can be customized by passing a map of LOG_EVENT types to hex color strings when calling getInstance(). Default colors are:

    • ERROR: 9c0006 red
    • WARN: ed7d31 orange
    • INFO: 548235 green
    • TRACE: 7f7f7f gray
    defaultLogEventFactoryFun: LogEventFactory

    Default factory function to create LogEvent instances. Used in case it was not set before by the user.

    Methods

    • To ensure when invoking clearInstance method in a sub-class it also clears (null) the last log event sent to the appender.

      Returns void

      Mainly intended for testing purposes. The state of the singleton will be lost. This method is available only in src folder, it is not deployed in dist folder (production).

    • Returns the map of event types to font colors used by this appender.

      Returns Record<LOG_EVENT, string>

      A defensive copy of the event fonts map.

      The keys are LOG_EVENT enum values, and the values are hex color strings.

    • Returns the Excel range where log messages are written. This range must be a single cell, and it is used to display log messages.

      Returns any

      The ExcelScript.Range object representing the message cell range.

      This is the cell where log messages will be displayed.

    • Log a LogEvent or build a log event using a message string with event type, and if present, with extra fields. It implements both the log methods from the Appender interface, since in Typescript doesn't allow you to overload methods with the same name but with different signatures.

      Parameters

      • arg1: string | LogEvent

        LogEvent or message string.

      • Optionalarg2: LOG_EVENT

        LOG_EVENT type. Only required if arg1 is a string.

      • Optionalarg3: LogEventExtraFields

        extraFields, only used if arg1 is a string.

      Returns void

      ScriptError if:

      • arg1 is a string but arg2 is not provided or is not a valid LOG_EVENT.
      • if the arg1 is not a string and arg1 is not a valid LogEvent.
      • If arg1 is a string, it creates a new LogEvent using the provided message and event type, and if presents extraFields.
      • If arg1 is already a LogEvent, it validates the event and sends it directly.
      • The method uses the static layout to format the log event before sending it to the appenders.
      • The arg3 parameter is optional and can be used to provide extra fields to create a log event, if arg1 is a string.
      • The Template pattern is used, i.e. it implements common logic for logging, but delegates the actual sending of the log event to the sendEvent abstract method. Therefore subclasses must implement the sendEvent method to define how the log event is sent.
      // Example: Log an error message with a custom event type and extra fields.
      const appender = new ConsoleAppender() // Assuming ConsoleAppender extends AbstractAppender
      appender.log("An error occurred", LOG_EVENT.ERROR, { user: "dlealv", id: 42 })
      // Example: Log a warning event directly.
      const warningEvent = new LogEventImpl("This is a warning", LOG_EVENT.WARNING)
      appender.log(warningEvent) // Directly log a LogEvent instance
    • Sets the value of the cell, with the event message, using the font defined for the event type, if not font was defined it doesn't change the font of the cell.

      Parameters

      • event: LogEvent

        a value from enum LOG_EVENT.

      • Optionalcontext: string

        (Optional) A string to provide additional context in case of an error. If not provided, it uses the class name and method name as context.

      Returns void

      ScriptError In case event is not a valid LogEvent.

    • Set the last log event sent to the appender.

      Parameters

      • event: LogEvent

        The log event to be sent.

      Returns void

      ScriptError if:

      • The event is not a valid LogEvent.

      Subclasses must call setLastLogEvent(event) after successfully sending the event, otherwise getLastLogEvent() will not reflect the most recent log event.

    • Shows instance configuration plus the message cell range address, the event fonts used, plus the parent information provided by toString method.

      Returns string

      A string representation of the appender.

      ScriptError, if the singleton was not instantiated.

    • Sets to null the singleton instance, useful for running different scenarios. It also sets to null the parent property lastLogEvent, so the last log event is cleared.

      Returns void

      const activeSheet = workbook.getActiveWorksheet() // workbook is input argument of main
      const msgCellRng = activeSheet.getRange("C2")
      appender = ExcelAppender.getInstance(msgCellRng) // with default log event colors
      appender.log("info event", LOG_EVENT.INFO) // Output: In cell C2 with green color: "info event"
      // Now we want to test how getInstance() can throw a ScriptError,
      // but we can't because the instance was already created and it is a singleton we need clearInstance
      appender.clearInstance()
      appender = ExcelAppender.getInstance(null) // throws a ScriptError

      Mainly intended for testing purposes. The state of the singleton will be lost. This method is available only in src folder, it is not deployed in dist folder (production).

    • Sets to null the static layout, useful for running different scenarios.

      Returns void

      Mainly intended for testing purposes. The state of the singleton will be lost. This method is available only in src folder, it is not deployed in dist folder (production).

    • Sets to null the log event factory, useful for running different scenarios.

      Returns void

      Mainly intended for testing purposes. The state of the singleton will be lost. This method is available only in src folder, it is not deployed in dist folder (production).

    • Returns the singleton ExcelAppender instance, creating it if it doesn't exist. On first call, requires a valid single cell Excel range to display log messages and optional color customizations for different log events (LOG_EVENT). Subsequent calls ignore parameters and return the existing instance.

      Parameters

      • msgCellRng: any

        ExcelScript.Range where log messages will be written. Must be a single cell range and not null or undefined.

      • eventFonts: Record<LOG_EVENT, string> = ExcelAppender.DEFAULT_EVENT_FONTS

        Optional. A map of LOG_EVENT types to hex color codes for the font colors. If not provided, defaults to the predefined colors in DEFAULT_EVENT_FONTS. The user can provide just the colors they want to customize, the rest will use the default colors. These colors can be defined with or without # prefix.

      Returns ExcelAppender

      The singleton ExcelAppender instance.

      ScriptError if:

      • msgCellRng was not defined or if the range covers multiple cells
      • It is not a valid Excel range or the range doesn't represent a single cell.
      • The font colors are not valid hexadecimal values for colors
      const range = workbook.getWorksheet("Log").getRange("A1")
      let excelAppender = ExcelAppender.getInstance(range)
      excelAppender.log("info event", LOG_EVENT.INFO)
      // Example using custom colors for errors events for the rest it uses the default colors:
      const customFonts: Record<LOG_EVENT, string> = {
      [LOG_EVENT.ERROR]: "0000FF", // blue
      }
      excelAppender.clearInstance() // Clear the singleton instance
      excelAppender = ExcelAppender.getInstance(range, customFonts)
      excelAppender.log("custom colored error event", LOG_EVENT.ERROR) // Output: In cell A1 with blue color: "custom colored error event"
    • Returns Layout

      The layout associated to all events. Used to format the log event before sending it to the appenders. If the layout was not set, it returns a default layout (lazy initialization). The layout is shared by all events and all appenders, so it is static.

      Static, shared by all log events. Singleton.

    • Sets the layout associated to all events, the layout is assigned only if it was not set before.

      Parameters

      • layout: Layout

        The layout to set.

      Returns void

      ScriptError if the layout is not a valid Layout implementation.

    • Sets the log event factory function used to create LogEvent instances if it was not set before.

      Parameters

      • logEventFactory: LogEventFactory

        A factory function to create LogEvent instances. Must have the signature (message: string, eventType: LOG_EVENT) => LogEvent, i.e. LogEventFactory type. If not provided, a default factory function is used.

      Returns void

      ScriptError if the log event factory is not a valid function with the expected signature.

      // Example: Custom LogEvent to be used to specify the environment where the log event was created.
      let prodLogEventFactory: LogEventFactory
      = function prodLogEventFactoryFun(message: string, eventType: LOG_EVENT) {
      return new LogEventImpl("PROD-" + message, eventType) // add environment prefix
      }
      AbstractAppender.setLogEventFactory(prodLogEventFactory) // Now all appenders will use ProdLogEvent