It is good practice to have some audit log of what uses do in the application. Some versions ago Microsoft introduced the Change Log to log data changes. How about logging an action execution?
One of the built in solutions in Business Central can be used to solve this. We now have the Activity Log (Table 710).
To use the Activity Log we need to have a record to attach the activity log to. All our Apps have a Setup table that usually only have one record. I like to attach my Activity Log to that record.
To show the Activity Log from that record you can add this action to that record’s page.
action("ActivityLog")
{
ApplicationArea = All;
Caption = 'Activity Log';
Image = Log;
Promoted = true;
PromotedCategory = Process;
PromotedOnly = true;
Scope = "Page";
ToolTip = 'See the data activities for this App.';
trigger OnAction()
var
ActivityLog: Record "Activity Log";
begin
ActivityLog.ShowEntries(Rec);
end;
}
The logging part can be something like this.
local procedure LogActivity(ADVUpgradeProjTable: Record "ADV Upgrade Project Table"; Context: Text[30])
var
ActivityLog: Record "Activity Log";
Status: Option Success,Failed;
begin
if ADVUpgradeProject."App Package Id" <> ADVUpgradeProjTable."App Package Id" then begin
ADVUpgradeProject.SetRange("App Package Id", ADVUpgradeProjTable."App Package Id");
ADVUpgradeProject.FindFirst();
end;
ActivityLog.LogActivity(
ADVUpgradeProject,
Status::Success,
Context,
StrSubstNo('%1', ADVUpgradeProjTable."Data Upgrade Method"),
StrSubstNo('%1 (%2)', ADVUpgradeProjTable."App Table Name", ADVUpgradeProjTable."App Table Id"));
end;
We also have the possibility to log details. Both a text value and also from an in-stream.
ActivityLog.SetDetailedInfoFromText("Text variable");
ActivityLog.SetDetailedInfoFromStream("in Stream");
In Business Central we have information about the execution context. I pass that execution context into the LogActivity. This gives me information on the session that is executing the code.
local procedure GetExecutionContext(): Text[30]
var
SessionContext: ExecutionContext;
begin
SessionContext := Session.GetCurrentModuleExecutionContext();
case SessionContext of
SessionContext::Install:
exit(CopyStr(InstallationMsg, 1, 30));
SessionContext::Upgrade:
exit(CopyStr(UpgradeMsg, 1, 30));
SessionContext::Normal:
exit(CopyStr(UserContextMsg, 1, 30));
end;
end;
var
InstallationMsg: Label 'App Installation';
UpgradeMsg: Label 'App Upgrade';
UserContextMsg: Label 'Started by user';
Using this logic we can log all execution during install, upgrade and normal user cases. If we need information on the variables we can log them into the detailed information using either JSON or XML.