This function retrieves the location of the log within the project, similar to how error logs display stack traces. This makes it easier to navigate directly to the log’s source in the code, reducing search time.
String? _getParentMethodName() {
try {
throw Exception();
} catch (e, stackTrace) {
final frames = stackTrace.toString().split('\n');
var father = "";
var grandfather = "";
try {
final fatherFrame = frames[3];
father = fatherFrame.split(' ').last;
} catch (_) {}
try {
final grandfatherFrame = frames[4];
grandfather = grandfatherFrame.split(' ').last;
} catch (_) {}
return father == "" && grandfather == "" ? null : "$father${grandfather == "" ? grandfather : "\n$grandfather"}\n";
}
}
How It Works:
It generates an exception and captures the stack trace.
It extracts the method names from specific frames in the stack trace.
It returns the method names in a structured format, making it easier to locate the log’s origin.
This helps in debugging by directly pinpointing where the log was recorded.
Function: _print()
This function customizes log display by adding tags and flags for better classification.
String _print(Object? object, {String? tag, String? flag}) =>
(tag == null || tag == "") && (flag == null || flag == "")
? object.toString()
: tag != null && tag != "" && flag != null && flag != ""
? "$tag | ${flag.toUpperCase()} | $object"
: (tag == null || tag == "") && flag != null && flag != ""
? "${flag.toUpperCase()} | $object"
: "$tag | $object";
Usage Example:
If the log is related to an Activity Diagram, you might format it as:
ADS 4.4.6.0 | ACTIVITY DIAGRAM | get image screenshot
How It Works:
If both tag and flag are provided → Outputs tag | FLAG | message
If only flag is provided → Outputs FLAG | message
If only tag is provided → Outputs tag | message
If neither is provided → Retrieves the parent method’s name
Step 3: Initialize Logging in Your App
Set up the logging system in your main application file. Ensure you call the setUp method with the desired parameters.
const ourLogDiagram = "Activity Diagram";
void main() async {
WidgetsFlutterBinding.ensureInitialized();
MyLog myLog = MyLog();
await myLog.setUp(
path: 'path/to/your/logfile.txt', // Specify the path where you want to save the log file
printTime: true,
isLogging: true,
noteInfoFileLog: 'This is the log file for my Flutter app.',
);
// Example log usage
myLog.info('App started');
myLog.debug('Debugging info');
myLog.error('An error occurred');
myLog.info("ADS 4.4.7 | save image", flag: ourLogDiagram, tag: "Write log");
runApp(MyApp());
}
Step 4: Use Logging Methods
Use the logging methods provided in the MyLog class throughout your application to record messages at different levels (trace, debug, info, warning, error, fatal).
After running the app and generating logs, you can find the log file at the specified path (e.g., path/to/your/logfile.txt). Open the file to see the stored logs.