Here is the sample code to create or generate a CSV file using apex code. The below code will query all SetupAuditTrail object records and stored the generated CSV file in document object folder.
Usually Setup Audit Log in salesforce will provide only last six month of data. But when we need a specific range of logs, then we have to go for a custom logic.
The below query will provide specific date range of Audit logs,
Usually Setup Audit Log in salesforce will provide only last six month of data. But when we need a specific range of logs, then we have to go for a custom logic.
The below query will provide specific date range of Audit logs,
- SELECT CreatedDate, CreatedBy.Username, Display, Section, Action, DelegateUser FROM SetupAuditTrail WHERE CreatedDate >= 2016-09-10T00:00:00Z AND CreatedDate <= 2016-10-01T00:00:00Z ORDER BY CreatedDate DESC
Sample Batch Code
- global class SetupAuditTrailBatch implements Database.Batchable<sObject>, Database.Stateful {
- global String csvColumnHeader;
- global List<String> csvRowValues = new List<String>();
- global Database.QueryLocator start(Database.BatchableContext BC){
- //Query all SetupAuditTrail records.
- String query = 'SELECT CreatedDate, CreatedBy.Username, Display, Section, Action, DelegateUser, CreatedById, CreatedBy.Name FROM SetupAuditTrail ORDER BY CreatedDate DESC';
- return Database.getQueryLocator(query);
- }
- global void execute(Database.BatchableContext BC, List<sObject> scope){
- //Process retrieved SetupAuditTrail records and format field values.
- for(SetupAuditTrail currSetupAudit : (List<SetupAuditTrail>) scope){
- String formattedDate = currSetupAudit.CreatedDate.format('M/d/yyyy h:mm:ss a z');
- String userName = currSetupAudit.CreatedBy.Username != null ? currSetupAudit.CreatedBy.Username : '';
- String displayVal = currSetupAudit.Display != null ? String.valueOf(currSetupAudit.Display).escapeCsv() : '';
- String sectionVal = currSetupAudit.Section != null ? currSetupAudit.Section : '';
- String delegateUser = currSetupAudit.DelegateUser != null ? currSetupAudit.DelegateUser : '';
- String rowStr = formattedDate + ',' + userName + ',' + displayVal + ',' + sectionVal + ','+ delegateUser;
- csvRowValues.add(rowStr);
- }
- }
- global void finish(Database.BatchableContext BC){
- List<Folder> folders = [SELECT Id, Name FROM Folder WHERE Name = 'Setup Audit Trail Logs'];
- if(!folders.isEmpty()){
- String documentName = 'SetupAuditTrailLog-'+ Datetime.now().format('MMM') + Datetime.now().year();
- csvColumnHeader = 'Date, User, Action, Section, Delegate User\n';
- String csvFile = csvColumnHeader + String.join(csvRowValues,'\n');
- // Insert the generated CSV file in Document object under "Setup Audit Trail Logs".
- Document doc = new Document(Name = documentName, Body = Blob.valueOf(csvFile), FolderId = folders[0].Id, Type = 'csv', ContentType='application/vnd.ms-excel');
- insert doc;
- }
- }
- }
References:
Supported calls:
query(), retrieve()
Note:
Aggregate queries aren’t supported on this object. For example, SELECT count() FROM SetupAuditTrail works but SELECT count(Id) FROM SetupAuditTrail fails.
very informative blog and useful article thank you for sharing with us , keep posting learn more aboutsalesforce training,salesforce online training
ReplyDeleteHI,I implemented this logic to create a csv file based on LastModifiedDate.It did generate the file correctly with all values.Today when I ran the batch it is creating a csv bt does not have any values.I queried and there are 3 records based on the soql.I am posting my code below,any help is highly appreciated since I need to get it up and running soon.
ReplyDeleteglobal class BatchGenerateUpdatedMeterFile implements Database.Batchable, Database.Stateful
{
global String csvColumnHeader;
global List csvRowValues = new List();
global Database.QueryLocator start(Database.BatchableContext BC)
{
//Query all modified meter records
Date dt = date.today();
System.debug(dt);
String query = 'SELECT Id,Name,parcel__r.Name, Module_Number__c,Meter_Install_Date__c from sm1e__smEquipment__c WHERE LastModifiedDate = Today';
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC ,List scope)
{
//Process retrieved records and format field values.
for(sm1e__smEquipment__c currentList : (List) scope){
String parcelName = currentList.parcel__r.Name;
System.debug(parcelName);
String moduleNumber = currentList.Module_Number__c;
Date meterInstallDate = currentList.Meter_Install_Date__c;
String meternumber = currentList.Name;
String rowStr = meternumber + ',' + parcelName + ',' + moduleNumber ;
csvRowValues.add(rowStr);
}
}
global void finish(Database.BatchableContext BC)
{
List folders = [SELECT Id, Name FROM Folder WHERE Name = 'BeaconExportFolder'];
if(!folders.isEmpty()){
String documentName = 'MeterDataExportFile-'+Datetime.now().format('dd/MM/yyyy');
csvColumnHeader = 'MeterNumber , Address ,ModuleNumber ,InstallDate \n';
String csvFile = csvColumnHeader + String.join(csvRowValues,'\n');
//Insert the genertaed CSV file in Document object under 'BeaconExportFolder'
Document doc = new Document(Name = documentName, Body = Blob.valueOf(csvFile),FolderId = folders[0].id,
Type = 'csv', ContentType ='application/vnd.ms-excel');
insert doc;
System.debug('File inserted');
}
}
}
I figured it out.The batch apex was taking time to complete.
ReplyDeleteVery good points you wrote here..Great stuff...I think you've made some truly interesting points.Keep up the good work. Free TikTok Fans
ReplyDeleteThanks for sharing this great information on Oracle APEX. Actually I was looking for the same information on internet for Oracle Apex Interview Questions and Answers and came across your blog. I am impressed by the information that you have on this blog. It shows how well you understand this subject, you can learn more about Oracle PPM Cloud by attending Oracle APEX Training.
ReplyDeleteThis was exactly what I needed. The Database.Stateful in the class header is a must. If it is not there, csvRowValues loses scope in the finish routine and will be blank. Only took me 1 hour to find that missing piece in my code. Thanks again for posting this.
ReplyDeleteVery nice information
ReplyDeleteSalesforce CPQ Training
Salesforce CPQ Online Training
I was looking for similar type of example, its a very good once. Thanks a lot.
ReplyDeleteSalesforce Service Cloud is about ensuring that businesses provide exceptional customer service. It's like having a virtual customer care team on hand 24 hours a day, seven days a week. Salesforce Service Cloud Implementation can be a challenging yet rewarding experience, but it is important to streamline their customer service operations, improve their agent productivity, and ultimately enhance their overall customer experience.
ReplyDeleteWith Salesforce Service Cloud Implementation, you can easily assist your businesses to leverage the power of Salesforce to achieve your business goals. Request a free consultation with an AblyPro expert to learn how Salesforce Service Cloud may help your company improve customer service and drive higher retention rates!
Great tutorial! Generating CSV files in Apex code in Salesforce is a practical way to extract Setup Audit Trail records for reporting or compliance purposes. This method can also be very useful when you need to migrate data from Salesforce to Zoho CRM efficiently. Clear examples like these make it much easier for developers to implement.
ReplyDeleteA python language course builds strong programming fundamentals with structured guidance. It explains syntax, loops, and data structures clearly. This python language course focuses on practical coding exercises. It enhances logical thinking and debugging skills. Learners gain real-time implementation knowledge. It is reliable and career-oriented.
ReplyDeleteMuleSoft Classes provide hands-on training for developers and IT professionals who want to learn API development and system integration. These classes cover Mule 4 fundamentals, DataWeave transformations, API design, and deployment strategies. With expert instructors and real-time projects, MuleSoft classes help learners build practical integration skills and prepare for MuleSoft certification exams.mulesoft classes
ReplyDeleteTableau online training offers detailed knowledge of business intelligence tools and visualization techniques. It explains data connections and dashboard publishing clearly. This tableau online training improves analytical thinking and reporting accuracy. Learners gain real-time project experience. Practical labs are included. Certification guidance is provided. It prepares industry-ready professionals.
ReplyDeleteI really like how the Ab Initio course content includes practical topics like data transformation, joins, sorting, and workflow execution.
ReplyDeleteab initio course contentThese skills are crucial for building real-world ETL pipelines and managing enterprise data systems.
A well-structured Mule software training program helps developers understand enterprise integrations, API design, and data transformations in a practical way.mule software training
ReplyDeleteThanks for the guide! Getting a Mule Soft certification definitely looks like a great way to boost career opportunities.mule soft certification
ReplyDeleteNice post! I’ve been searching for interactive mulesoft classes, and this article gave useful insights into what to expect from training.mulesoft classes
ReplyDeleteHelpful post! ServiceNow administrator training is essential for mastering platform configuration and automation
ReplyDeleteservicenow administrator training.
MuleSoft training offers hands-on experience with API integration, enabling you to connect applications and data seamlessly. Enroll now and gain the knowledge to become an in-demand MuleSoft developer!mulesoft training
ReplyDeleteExcellent information! Service Now trainings are highly useful for professionals aiming to upskill in ITSM tools.
ReplyDeleteservice now trainings
Nice post! Mulesoft developer training equips learners with practical skills in building, testing, and deploying APIs effectively.mulesoft developer training
ReplyDeleteGreat article! If you’re looking for a Mulesoft developer course online, OnlineITGuru offers flexible schedules and expert support.Mulesoft developer course online
ReplyDeleteGreat insights into Salesforce CPQ training online. I like how it emphasizes flexibility and hands-on experience for working professionals.
ReplyDeletelearn salesforce cpq
Salesforce CPQ training is extremely valuable for professionals looking to streamline sales processes and pricing strategies.salesforce cpq training
ReplyDeleteThis MuleSoft course overview is very helpful. It clearly explains why API integration skills are in demand.mulesoft course
ReplyDeleteMule software training is trending now, and this blog provides a good introduction.mule software training
ReplyDeleteMule Soft certification is highly valuable in today’s job market. This blog explains its benefits clearly.mule soft certification
ReplyDeleteMuleSoft certification can boost career growth, and this article explains its importance well.mule soft certification
ReplyDeleteOnline MuleSoft training allows learners to gain integration skills without disrupting their schedules.mulesoft online training
ReplyDelete