Skip to content

Instantly share code, notes, and snippets.

@megasmack
Last active June 9, 2023 16:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save megasmack/0d78fc6044122aa333c6668abf1a5800 to your computer and use it in GitHub Desktop.
Save megasmack/0d78fc6044122aa333c6668abf1a5800 to your computer and use it in GitHub Desktop.
LWC/Apex Retrieve User Debug Mode Console Logs

LWC/Apex User Debug Mode Console Logs

Using the Debug Mode setting in the running User to send debug console logs to the Inspector for Lightning Web Components.

If you need to override the debug behavior, you can change the userDebugMode sessionStorage property to 'true'. You might need to do this to get logs for Guest users that do not have a Debug Mode.

import checkUserDebugMode from '@salesforce/apex/UserDebugMode.checkUserDebugMode';
/**
* Get User Debug Mode from Apex and store in sessionStorage.
* @returns {Promise<boolean>}
*/
const getUserDebugMode = async () => {
let userDebugMode = sessionStorage.getItem('userDebugMode');
// If the sessionStorage is not set,
// get the User's Debug settings from Apex.
if (!userDebugMode) {
userDebugMode = await checkUserDebugMode();
// Convert boolean to string for sessionStorage.
userDebugMode =
typeof userDebugMode === 'boolean' ? `${userDebugMode}` : undefined;
sessionStorage.setItem('userDebugMode', userDebugMode);
if (userDebugMode === 'true') {
// eslint-disable-next-line no-console
console.log('%cUser Debug Mode Enabled', 'color:green');
}
}
// Convert string to boolean.
return userDebugMode === 'true';
};
/**
* Sends console message based on debug mode.
*/
class debugUtil {
/**
* Sends console message based on debug mode.
* @param {string} type
* @param messages
* @returns {Promise<void>}
*/
static logMessage = async (type, messages) => {
const isDebugMode = await getUserDebugMode();
if (isDebugMode) {
const args = Array.prototype.slice.call(messages);
// eslint-disable-next-line no-console,prefer-spread
console[type].apply(console, args);
}
};
/**
* Sends console.log messages based on debug mode.
*/
static log(...args) {
this.logMessage('log', args);
}
/**
* Sends console.warn messages based on debug mode.
*/
static warn(...args) {
this.logMessage('warn', args);
}
/**
* Sends console.error messages based on debug mode.
*/
static error(...args) {
this.logMessage('error', args);
}
}
export { getUserDebugMode, debugUtil };
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>56.0</apiVersion>
<description>Debug Util</description>
<isExposed>false</isExposed>
<masterLabel>Debug Util</masterLabel>
</LightningComponentBundle>
import { LightningElement } from 'lwc';
import someApexmethod from '@salesforce/apex/SomeApexClass.someApexmethod';
import { debugUtil } from 'c/debugUtil';
export default class ExampleLwc extends NavigationMixin(LightningElement) {
// --- Lifecycle hooks ---
connectedCallback() {
this.getData();
}
// --- Private methods ---
getData() {
someApexmethod()
.then((response) => {
// Do whatever with the data.
const data = {...response};
// Log out result only if user has debug mode.
debugUtil.log('someApexmethod Data: ', data);
debugUtil.warn('You can also send warnings');
debugUtil.error('and errors.');
}
.catch((error) => console.error(error));
}
}
public with sharing class UserDebugMode {
@AuraEnabled
public static Boolean checkUserDebugMode() {
User user = null;
if (Schema.SObjectType.User.fields.UserPreferencesUserDebugModePref.isAccessible()) {
user = [
SELECT UserPreferencesUserDebugModePref
FROM User
WHERE Id = :UserInfo.getUserId()
];
}
return user?.UserPreferencesUserDebugModePref;
}
}
@IsTest
private class UserDebugModeTest {
@IsTest static void testCheckUserDebugMode() {
Boolean isTrue = null;
Boolean isFalse = null;
// Create test system user
String uniqueUserName = 'standarduser' + Datetime.now().getTime() + '@testorg.com';
Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
User u = new User(Alias = 'standt', Email='standarduser@testorg.com',
EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
LocaleSidKey='en_US', ProfileId = p.Id,
TimeZoneSidKey='America/Los_Angeles',
Username=uniqueUserName, UserPreferencesUserDebugModePref = true);
// Perform the test
Test.startTest();
System.runAs(u) {
isTrue = UserDebugMode.checkUserDebugMode();
u.UserPreferencesUserDebugModePref = false;
update u;
isFalse = UserDebugMode.checkUserDebugMode();]
}
Test.stopTest();
// Test results
System.assertEquals(true, isTrue);
System.assertEquals(false, isFalse);
System.assertNotEquals(null, isFalse);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment