Service Messages
Service messages are specially constructed pieces of text that pass commands/information about the build from the build script to the TeamCity server.
To be processed by TeamCity, they need to be written to the standard output stream of the build, that is printed or echoed from a build step.
Examples:
A single service message cannot contain a newline character inside it, it cannot span across multiple lines.
Service Messages Formats
Service messages support two formats:
Single-attribute message:
##teamcity[<messageName> 'value']Multiple-attribute message:
##teamcity[<messageName> name1='value1' name2='value2']Multiple-attribute message can more formally be described as:
##teamcity[messageNameWSPpropertyNameOWSP=OWSP'value'WSPpropertyName_IDOWSP=OWSP'value'...OWSP]
where:
messageName
is the name of the message, such asflowStarted
orsetParameter
.propertyName
is a name of the message attribute. Must be a valid Java ID.value
is a value of the attribute. Must be an escaped value.WSP
is a required whitespace(s): space or tab character (\t
).OWSP
is an optional whitespace(s)....
is any number ofWSPpropertyNameOWSP=OWSP'value'
blocks.
Escaped Values
For escaped values, TeamCity uses a vertical bar |
as an escape character. To have certain special characters properly interpreted by the TeamCity server, they must be preceded by a vertical bar. For example, the following message:
will be displayed in TeamCity as foo's test
. Refer to the table of the escaped values below.
Character | Escape as |
---|---|
' (apostrophe) | |' |
\n (line feed) | |n |
\r (carriage return) | |r |
\uNNNN (unicode symbol with code 0xNNNN) | |0xNNNN |
| (vertical bar) | || |
[ (opening bracket) | |[ |
] (closing bracket) | |] |
Reporting Messages to Build Log
You can report messages to a build log as follows:
where:
status
can take the following values:NORMAL
(default),WARNING
,FAILURE
,ERROR
.errorDetails
is used only ifstatus
isERROR
, in other cases it is ignored.
This message fails the build in case its status isERROR
and the " Fail build if an error message is logged by build runner " box is checked on the Build Failure Conditions page of the build configuration. For example:##teamcity[message text='Exception text' errorDetails='stack trace' status='ERROR']
Blocks of Service Messages
Blocks are used to group several messages in the build log.
Block opening:
The blockOpened
system message has the name
attribute, and you can also add its description:
Block closing:
Reporting Compilation Messages
where:
compiler_name
is an arbitrary name of the compiler performing compilation, for example,javac
orgroovyc
. Currently, it is used as a block name in the build log.Any message with status
ERROR
reported betweencompilationStarted
andcompilationFinished
will be treated as a compilation error.
Message FlowId
Any message supports the optional attribute flowId
. In the following examples, <messageName>
is the name of the specific service message.
flowId
is a unique identifier of the message flow in a build. Flow tracking is necessary, for example, to distinguish separate processes running in parallel. The identifier is a string that must be unique in the scope of an individual build.
In most cases, flowId
is the only attribute required to start a message flow.
When you absolutely need to start a flow not inside the root flow but as a subflow inside an existing flow, add the flowStarted
parameter and specify the parent flow ID as the parent
parameter. Flows without the specified parent start inside the root flow of the current step.
To end a subflow, use the flowFinished
parameter. Ending a parent flow automatically closes all its subflows, but we recommend declaring the flow order explicitly:
This custom subflow order affects the sequence of reports in a build log and allows reporting results as subtrees.
Reporting Tests
To use the TeamCity on-the-fly test reporting, a testing framework needs dedicated support for this feature to work (alternatively, XML Report Processing can be used). If TeamCity doesn't support your testing framework natively, it is possible to modify your build script to report test runs to the TeamCity server using service messages. This makes it possible to display test results in real-time, make test information available on the Tests tab of the Build Results page.
Message Creation Timestamp
Test report messages support the optional attribute timestamp
. In the following examples, <messageName>
is the name of the specific service message.
The timestamp format is yyyy-MM-dd'T'HH:mm:ss.SSSZ
or yyyy-MM-dd'T'HH:mm:ss.SSS
according to Java SimpleDateFormat syntax.
Example:
For .NET DateTimeOffset, a code like this
will result in
Supported Test ServiceMessages
Test suite messages: Test suites are used to group tests. TeamCity displays tests grouped by suites on the Tests tab of the Build Results page and in other places.
All the individual test messages are to appear between testSuiteStarted
and testSuiteFinished
(in that order) with the same name
attributes.
Nested Test Reporting
Starting another test finishes the currently started test in the same flow. To still report tests from within other tests, you will need to specify another flowId
in the nested test service messages.
Test start/stop messages:
Indicates that testName
was run. If the testFailed
message is not present, the test is regarded successful, where
duration
(optional numeric integer attribute) sets the test duration in milliseconds to be reported in TeamCity UI. If omitted, the test duration will be calculated from the messages timestamps. If the timestamps are missing — from the actual time the messages were received on the server.captureStandardOutput
(optional boolean attribute) — iftrue
, all the standard output and standard error messages received betweentestStarted
andtestFinished
messages will be considered test output. The default value isfalse
: assumes usage oftestStdOut
andtestStdErr
service messages to report the test output.
It is highly recommended that you ensure that the pair of test suite
+ test name
is unique within the build. For advanced TeamCity test-related features to work, test names must not deviate from one build to another (a single test must be reported under the same name in every build). Include absolute paths in the reported test names is strongly discouraged.
Ignored tests:
Indicates that testName
is present but was not run (was ignored) by the testing framework. As an exception, the testIgnored
message can be reported without the matching testStarted
and testFinished
messages.
Test output:
The testStdOut
and testStdErr
service messages report the test's standard and error output to be displayed in the TeamCity UI. There must be only one testStdOut
and one testStdErr
message per test. An alternative but a less reliable approach is to use the captureStandardOutput
attribute of the testStarted
message.
Test result:
Indicates that the testname
test failed. Only one testFailed
message can appear for a given test name.
message
contains the textual representation of the error.details
contains detailed information on the test failure, typically a message and an exception stacktrace.actual
andexpected
attributes can only be used together withtype='comparisonFailure'
to report comparison failure. The values will be used when opening the test in the IDE.
Here is a longer example of test reporting with service messages:
Enabling Test Retry
You can enable the support of test retry for a build configuration. With this option enabled, the successful run of a test will mute its previous failure, which means that TeamCity will mute a test if it fails and then succeeds within the same build.
Such tests will not affect the build status.
Interpreting Test Names
A full test name can have a form of: <suite name>: <package/namespace name>.<class name>.<test method>(<test parameters>)
, where <class name>
and <test method>
cannot have dots in the names. Only <test method>
is a mandatory part of a full test name.
The full test name is used to compare tests between consequent builds or match tests across different build configurations.
Example of a full test name:
The Tests tab of the Build Results page allows grouping by suites, packages/namespaces, classes, and tests. Usually the attribute values are provides as they are reported by your test framework and TeamCity is able to interpret test names correctly.
If a test cannot be parsed in the form above, TeamCity still tries to extract <suite name>
from the full test name for the filtering on the Tests tab, and treats everything after the suite a non-parsable test name.
Reporting Additional Test Data
It is possible to attach extra information to the tests using the testMetadata
service message. More details are available on a separate page.
Reporting .NET Code Coverage Results
You can configure .NET coverage processing by means of service messages. To learn more, refer to Manually Configuring Reporting Coverage page.
Reporting Inspections
You can report inspections from a custom tool to TeamCity using the service messages described below.
Among other uses, the number of inspections can be used as a build metric to fail a build on.
Inspection Type
Each specific warning or an error in code (inspection instance) has an inspection type — the unique description of the conducted inspection, which can be reported via
where all the attributes are required and can have either numeric or textual values:
id
— (mandatory) limited by 255 charactersname
— (mandatory) limited by 255 characterscategory
— (mandatory) limited by 255 characters. Thecategory
attribute examples are "Style violations" and "Calling contracts".description
— (mandatory) limited by 4000 characters. The description can also be in HTML. For example,
Inspection Instance
Reports a specific defect, warning, error message. Includes location, description, and various optional and custom attributes.
where all the attributes can have either numeric or textual values:
typeId
— (mandatory), reference to theinspectionType.id
described above limited by 255 characters.message
— (optional) current instance description limited by 4000 characters.file
— (mandatory) file path limited by 4000 characters. The path can be absolute or relative to the checkout directory.line
— (optional) line of the file, integer.additional attribute
– can be any attribute,SEVERITY
is often used here, with one of the following values (mind the upper case):INFO
,ERROR
,WARNING
,WEAK WARNING
.
Example:
Publishing Artifacts While Build is in Progress
You can publish the build artifacts while the build is still running, immediately after the artifacts are built.
To do this, you need to output the following line:
The <path>
has to adhere to the same rules as the Build Artifact specification of the Build Configuration Settings. The files matching the <path>
will be uploaded and visible as the artifacts of the running build.
The message should be printed after all the files are ready and no file is locked for reading.
Artifacts are uploaded in the background, which can take time. Make sure the matching files are not deleted till the end of the build (for example, you can put them in a directory that is cleaned on the next build start, in a temp directory, or use Swabra to clean them after the build).
Artifacts that are specified in the build configuration setting will be published as usual.
Passing NuGet Packages Between Steps
If you need to publish NuGet packages and then use their contents within one build, you want to guarantee they are published and indexed on time — and not at the build finish.
For this, you can use a NuGet Publish runner or send the ##teamcity[publishNuGetPackage]
service message in any step instead. This ensures the NuGet packages are published in all configured NuGet feeds right at the end of the current step and are available in the following build steps.
Reporting Build Progress
You can use special progress messages to mark long-running parts in a build script. These messages will be shown on the projects' dashboard for the corresponding build and on the Build Results page.
To log a single progress message, use:
This progress message will be shown until another progress message occurs or until the next target starts (in case of Ant builds).
If you wish to show a progress message for a part of a build only, use:
Reporting Build Problems
To fail a build directly from the build script, a build problem must be reported. Build problems affect the build status text. They appear on the Build Results page. To add a build problem to a build, use:
where:
description
(mandatory): a human-readable plain text describing the build problem. By default, thedescription
appears in the build status text and in the list of build's problems. The text is limited to 4000 symbols, and will be truncated if the limit is exceeded.identity
(optional): a unique problem ID. Different problems must have different identity, same problems — same identity, which should not change throughout builds if the same problem, for example, the same compilation error occurs. It must be a valid Java ID up to 60 characters. If omitted, theidentity
is calculated based on thedescription
text.
Reporting Build Status
Use the buildStatus
to set the build status text.
Unlike progress messages designed to reflect currently ongoing operations in the build status, a buildStatus
message sets the final build status that persists after a build finishes.
You can add separate steps with different step execution conditions to differentiate "green" builds from failing ones, and set different custom statuses for each of them.
The default status text can be referenced via the {build.status.text}
placeholder.
The Status Parameter
The optional status
parameter of the buildStatus
service message allows you to override the appearance of the build: paint failed builds as successful and (not recommended) successful builds as failed.
To change the build's status from failed to successful, add the
status='SUCCESS'
parameter.##teamcity[buildStatus status='SUCCESS' text='{build.status.text}, the build is marked as successful']If you want a "green" build to appear as failed, you can send the following message:
##teamcity[buildStatus status='FAILURE' text='The build status was manually switched to {build.status.text}']However, since that only changes the build status and does not provide any actionable insights to anyone investigating this "failed" build, we recommend sending the
buildProblem
message instead. This message allows you to genuinely fail the build (and provide specific details related to this issue) rather than merely changing the final status. As a result, project maintainers will be able to use the variety of tools TeamCity offers for resolving issues: investigations, mutes, and so on.##teamcity[buildProblem description='The artifact size has decreased dramatically' identity='2281488']
Reporting Build Number
To set a custom build number directly, specify a buildNumber
message using the following format:
In the <new build number> value, you can use the {build.number}
substitution to use the current build number automatically generated by TeamCity. For example:
Adding or Changing Build Parameter
By using a dedicated service message in your build script, you can dynamically update build parameters of the build right from a build step (the parameters need to be defined in the Parameters section of the build configuration). The changed build parameters will be available in the build steps following the modifying one. They will also be available as build parameters and can be used in the dependent builds via %\dep.*% parameter references
, for example:
When specifying a build parameter's name, mind the prefix:
system
for system properties.env
for environment variables.No prefix for configuration parameters.
Read more about build parameters and their prefixes.
Reporting Build Statistics
In TeamCity, it is possible to configure a build script to report statistical data and then display the charts based on the data. Refer to the Customizing Statistics Charts page for a guide to displaying the charts on the web UI. This section describes how to report the statistical data from the build script via service messages. You can publish the build statics values in two ways:
Using a service message in a build script directly
Providing data using the teamcity-info.xml file
To report build statistics using service messages: Specify a
buildStatisticValue
service message with the following format for each statistics value you want to report:
where
key
must not be equal to any of predefined keys.value
must be a positive/negative integer of up to 13 digits; float values with up to 6 decimal places are also supported.
Disabling Service Messages Processing
If you need for some reason to disable searching for service messages in the output, you can disable the service messages search with the messages:
Any messages that appear between these two are not parsed as service messages and are effectively ignored. For server-side processing of service messages, enable/disable service messages also supports the flowId
attribute and will ignore only the messages with the same flowId
.
Importing XML Reports
In addition to the UI build feature, XML reporting can be configured from within the build script with the help of the importData
service message. Also, the message supports importing of the previously collected code coverage and code inspection/duplicates reports.
The service message format is:
where typeID
can be one of the following (see also XML Report Processing):
typeID | Description |
---|---|
Testing frameworks | |
| JUnit Ant task XML reports |
| Maven Surefire XML reports |
| NUnit-Console XML reports |
| MSTest XML reports |
| VSTest XML reports |
| Google Test XML reports |
Code inspection | |
| IntelliJ IDEA inspection results |
| Checkstyle inspections XML reports |
| FindBugs inspections XML reports |
| JSLint XML reports |
| ReSharper |
| FxCop inspection XML reports |
| PMD inspections XML reports |
Code duplication | |
| PMD Copy/Paste Detector (CPD) XML reports |
| ReSharper |
Code coverage | |
| XML reports generated by dotcover, partcover, ncover or ncover3 |
Notes:
Only supports a specific file in the
path
attribute.Also requires the
findBugsHome
attribute specified pointing to the home directory of the installed FindBugs tool.Also requires the
tool='<tool name>'
service message attribute, where the<tool name>
is eitherdotcover
,partcover
,ncover
orncover3
.
If not specially noted, the report types support Ant-like wildcards in the path
attribute.
verbose='true'
attribute will enable detailed logging into the build log.parseOutOfDate='true'
attribute will process all the files matching the path. By default, only those updated during the build (determined by last modification timestamp) are processed. If any not matching reports are found, the "report skipped as out-of-date" message appears in the build log.whenNoDataPublished=<action>
(where<action>
is one of the following:info
(default),nothing
,warning
,error
) will change output level if no reports matching the path specified were found.(deprecated, use Build Failure Conditions instead)
findBugs
,pmd
orcheckstyle
importData messages also take optionalerrorLimit
andwarningLimit
attributes specifying errors and warnings limits, exceeding which will cause the build failure.
To initiate monitoring of several directories or parse several types of the report, send the corresponding service messages one after another.
Writing the File into the Build Log
Send the following service message to start tracking the contents of a file and write its new lines to the build log.
type
— always equals 'streamToBuildLog'.filePath
— the path to the specific file. This path can be absolute (filePath='%teamcity.build.checkoutDir%/temp.txt'
) or relative (filePath='./myFolder/temp.txt'
). Relative paths are resolved under the current working directory of the agent that runs the build (the directory returned by theteamcity.agent.work.dir
parameter). If the specified file does not exist or cannot be opened, TeamCity will periodically retry to access this file (for as long as the runner that sent this service message is still running).
wrapFileContentInBlock
(optional) — specifies whether the output of this message should be placed in a collapsible "Streaming file..." block. The default value is "true".charset
(optional) — a canonical name or an alias of an encoding supported by Java. If the argument is absent or the encoding cannot be resolved, UTF-8 is used.
TeamCity monitors the given file for as long as the parent runner is active. When the runner stops, the file is streamed to its end and closed.
Sending Custom Slack Messages
You can use TeamCity service messages to send Slack direct messages and post updates in Slack channels.
TeamCity utilizes Slack connections to send Slack messages. If you do not already have a Slack connection, go to Administration | Project Settings | Connections and create one.
Open the settings of a Slack connection and set the Notifications limit to any positive number. This value specifies the maximum number of messages that build configurations can send per run.
For security reasons, only links to the same TeamCity server are allowed in messages. Messages with URLs to external web resources are automatically blocked with a corresponding message written to the "teamcity-notifications.log" file (Administration | Diagnostics | Server Logs).
If you need to include links to external resources, enter their hostnames in the Allowed hostnames field. Use comma (,) as a separator to enter multiple values and asterisk (*) as a wildcard for any string (for example, *.test.co.uk).
Once a Slack connection is configured, you can add service messages to a build script in the following format:
##teamcity[notification notifier='slack' message='Line 1 |rLine2 |rLine3' sendTo='build_farm_alerts' connectionId='PROJECT_EXT_2']notifier
— always equals "slack".message
— the message to show. Supports Markdown syntax (apart from "\n" for line breaks, use "|n" or "|r" instead).sendTo
— specifies who should receive the message. Accepts a single Slack channel name, channel ID (starts with "C", for instance, "C052UHDRZU7"), or user ID (starts with "U", for instance, "U02K2UVKJP7") as value. If you need to send the same message to multiple recipients, create multiple service messages with differentsendTo
values.connectionID
— the optional parameter that allows you to choose a specific Slack connection that TeamCity should use to send this message. Accepts connection IDs as values. If this parameter is not specified, TeamCity will retrieve all Slack connections available for the current project and choose the one whose Notifications limit is not zero.
Run the build to ensure all Slack messages are delivered.
Sending Custom Email Messages
You can use TeamCity service messages to send emails from inside build scripts.
Navigate to Administration | Email Notifier and set up common Notifier settings: the sender's email, SMTP login and password, connection security protocol, and others. See this link for an example: Setting up Google Mail as Notification Server.
Set the Notifications limit setting to any positive number. This value specifies the maximum number of messages that build configurations can send per run.
Enter the list of recipients to the Allowed addresses. Messages sent to recipients outside this list are automatically blocked. Use comma (,) as a separator to enter multiple addresses and asterisk (*) as a wildcard for any string (for example, *@gmail.com).
For security reasons, only links to the same TeamCity server are allowed in messages. Messages with URLs to external web resources are automatically blocked with a corresponding message written to the "teamcity-notifications.log" file (Administration | Diagnostics | Server Logs).
If you need to include links to external resources, enter their hostnames in the Allowed hostnames field. Use comma (,) as a separator to enter multiple values and asterisk (*) as a wildcard for any string (for example, *.test.co.uk).
Once an Email Notifier is set up, you can add service messages to a build script in the following format:
##teamcity[notification notifier='email' message='Message body' subject='Email subject' address='user1@gmail.com,user2@yourcompany.com']notifier
— always equals "email".message
— the message body in plain text format.subject
— the email subject.address
— one or multiple addresses from the Allowed addresses list of the Email Notifier.
Run the build to ensure all emails are delivered.
Canceling Build via Service Message
If you need to cancel a build from a script, for example, if a build cannot proceed normally due to the environment, or a build should be canceled form a subprocess, you can use the following service message:
If required, you can re-add the build to the queue after canceling it. By default, TeamCity will do 3 attempts to re-add the build into the queue.
Adding and Removing Build Tags
Service messages allow you to add and remove build tags.
##teamcity[addBuildTag 'your-custom-tag']
— adds a new tag to the current build.##teamcity[removeBuildTag 'tag-to-remove']
— removes a tag from the current build.
Both messages allow you to pass values of configuration parameters instead of plain strings. For example, the ##teamcity[addBuildTag '%teamcity.agent.jvm.os.name%']
message tags builds with names of operating systems installed on agent machines.
One service message can add or remove a single tag. To add or remove multiple tags, send multiple service messages.
Libraries Reporting Results via TeamCity Service Messages
Several platform-specific libraries from JetBrains and external sources are able to report the results via TeamCity Service messages.
Service messages .NET library — .NET library for generating (and parsing) TeamCity service messages from .NET applications. See a related blog post.
Jasmine 2.0 TeamCity reporter — support for emitting TeamCity service messages from Jasmine 2.0 reporter
Perl TAP Formatter — formatter for Perl to transform TAP messages to TeamCity service messages
PHPUnit 5.0 — supports TeamCity service messages for tests. For earlier PHPUnit versions, the following external libraries can be used: PHPUnit Listener 1, PHPUnit Listener 2 — listeners which can be plugged via PHPUnit's
suite.xml
to produce TeamCity service messages for tests.Python Unit Test Reporting to TeamCity — the package that automatically reports unit tests to the TeamCity server via service messages (when run under TeamCity and provided the testing code is adapted to use it).
Mocha — on-the-fly reporting via service messages for Mocha JavaScript testing framework. See the related post with instructions.
Karma — support in the JavaScript testing tool to report tests progress into TeamCity using TeamCity service messages.