Console Log Like A Pro In Gtm

Console Log Like A Pro In Gtm

Management Summary

Advanced and efficient console logging techniques in Google Tag Manager (GTM) are a game changer. They significantly improve the debugging process, make it easier to visually process and trace logs, and establish a certain quality standard in the development of (more extensive) custom HTML tags or custom JavaScript variables.

This blog article dives into advanced and efficient console logging techniques in Google Tag Manager (GTM). In the “Best practices” chapter I go into smart structuring and placement of the logs, with the “Advanced Logging” chapter optimizing the logs themselves.

Best practices for console logging in GTM

Structured logging

Structured logging in GTM refers to the systematic organization of console log messages to ensure clear and efficient traceability. Through the targeted use of meaningful tags and structures in the log entries, the causes of problems can be identified more easily and the debugging process can be accelerated.

It is important that an output occurs at crucial code points, for example intermediate values ​​that are further processed. It is also important to log where errors are expected. For example, in the catch block of a try-catch statement. Caught errors should always be logged and should not be caught without a way to detect the error.

Contextual information

Contextual logging refers to including additional information in log messages that more clearly presents the context of the GTM configuration or custom functions. This can include the inclusion of relevant variable values, states of conditions or specific information from the GTM configuration. The goal is to not only make log messages more informative, but also to provide more insight into the state and decisions within the GTM workflow.

Consistent logging

A consistent logging format is very helpful for effective error diagnosis and understanding code flow in GTM. Maintaining a consistent style in log messages improves readability and facilitates team collaboration.

Practical recommendations:

  • Uniform structure: Define a clear structure for log messages that remains consistent across all GTM tags and custom functions. For example:
console.log('[Category] - Message: ', message);
  • Use of wildcards: Use placeholders for dynamic content to increase the flexibility of log messages. For example:
console.log('Processing URL: %s', url);

Conditional console logging output

Conditional log messages enable precise output of log entries based on predefined criteria. This technique is designed to streamline the debugging process and make it easier to focus on relevant parts of the code, especially in complex GTM configurations. The aim is to reduce the logs to specific cases using if queries, for example, so as not to have too many messages in the console.

Advanced console logging techniques

Timestamps and performance measurements

Integrating timestamps and performance measurements into log messages in Google Tag Manager (GTM) enables detailed analysis of time-critical aspects during development.

Practical application using the example of a variable that processes URLs:

// Example: timestamp for the start of processing
console.log('Start processing at: ' + new Date().toLocaleTimeString() + ", " + new Date().getMilliseconds() + "." + performance.now().toString().split(."")[1] + " ms");
try {
  // Critical section of code
  processURL(url);
  // Further processing or tags here...
// Example: Timestamp for completion of processing
  console.log('Processing completed at: ' + new Date().toLocaleTimeString() + ", " + new Date().getMilliseconds() + "." + performance.now().toString().split(."")[1] + " ms");
} catch (error) {
  // Catch and log errors
  console.error('Error processing URL:', error, 'URL:', url);
} finally {
  // Example: timestamp for the final execution
  console.log('Execution completed at: ' + new Date().toLocaleTimeString() + ", " + new Date().getMilliseconds() + "." + performance.now().toString().split(."")[1] + " ms");
}

The integration of timestamps enables precise monitoring of the temporal processes in the GTM code. By logging timestamps before, during, and after critical code sections, developers gain a clear overview of performance and can identify potential bottlenecks.

Using performance.now() provides even more precise measurement of time periods:

var starttime = performance.now();
// Code to execute
var endtime = performance.now();
console.log('Time span:', end time - start time, 'Milliseconds');

Measuring the time periods enables a detailed analysis of performance bottlenecks and helps developers optimize the GTM code.

This technique is particularly useful for debugging race conditions where conflicts may occur. Precise time measurements can be used to identify potential bottlenecks and optimize the execution of GTM elements.

Console Logs CSS formatting

Console Logs CSS formatting in Google Tag Manager (GTM) is initiated by the %c character in the log message. This character signals to the console.log command that the output value is followed by a CSS format string that influences the display of the log message.

An example:

// Example: CSS formatting for a highlighted success message
console.log('%cSuccess: transaction completed', 'color: green; font-weight: bold;');

This example formats the text “Success: Transaction Complete” with a green color style and bold font. Through the targeted use of CSS formatting, important log messages can be highlighted and visually emphasized, which significantly improves readability and comprehensibility during troubleshooting in GTM.

More console functions

In addition to the well-known console.log function, there are other useful console functions such as console.dir and console.table. These advanced features enable more detailed inspection of objects and clear presentation of tabular data in the console.

Practical application of console.dir:

// Example: Using console.dir for a detailed display of objects
const auto = { Brand: 'Volkswagen', Model: 'Golf', Year: 2022 };
console.dir(auto);

The console.dir function enables a detailed representation of objects in the console, clearly displaying all properties and nested structures:

Object
  Year of construction: 2022
  Brand: "Volkswagen"
  Model: "Golf"
  __proto__: Object

Practical application of console.table:

// Example: Using console.table for tabular representation of data
const userdata = { Name: 'Max Sample', Age: 30, City: 'Sample City' };
console.table([userdata]);

The console.table function is ideal for clearly presenting data in tabular form. In this example, the user data is displayed as a table, which significantly improves readability, especially when working with large data sets or arrays:

┌────────────┬──────────────── ─┬─────────┬─────────────────┐
│ (index) │ Name │ Age │ City │
├────────────┼──────────────── ─┼─────────┼─────────────────┤
│ 0 │ 'Max Sample' │ 30 │ 'Example City' │
└────────────┴──────────────── ─┴─────────┴─────────────────┘

Conclusion

The debugging process is optimized by clearly structuring log messages, integrating contextual information and using consistent logging formats. Advanced techniques such as conditional log messages, timestamps, performance measurements, and the use of console.dir and console.table open up new possibilities for precise error analysis and resolution.

We are available at any time for customized tracking solutions and the implementation of complex tracking structures! Contact us:kontakt@e-dialog.group

e-dialog office Vienna
Relevant content

More about Analytics