0

Is there any easy way to read from and write to a file in Salesforce?. I want to store metadata, let's say something like log data of a user, by mimicking the functionality of log4j.

2 Answers 2

3

I have used the class below that creates a named Document in the "My Personal Documents" folder. You can call it like this:

Logger logger = new Logger();
try {
    logger.info('...');
    ...
    logger.error('...');
} finally {
    logger.flush('Log-' + System.currentTimeMillis());
}

But a fundamental problem is that if the transaction is rolled back (e.g. an unhandled exception) the update of the Document will also be rolled back.

public class Logger {

    private String text = '';

    public void info(String message) {
        text += 'INFO:  ' + message + '\n';
    }

    public void error(String message) {
        text += 'ERROR: ' + message + '\n';
    }

    public void flush(String documentName) {

        Document[] docs = [select Body from Document where Name = :documentName];

        // Append if exists or create
        Document doc = docs.size() == 1
                ? docs[0]
                : new Document(
                        FolderId = UserInfo.getUserId(), // "My Personal Documents" folder
                        Name = documentName,
                        Body = Blob.valueOf(''),
                        ContentType = 'text/plain',
                        Type = 'txt'
                        );

        doc.Body = Blob.valueOf(doc.Body.toString() + text);
        upsert doc;

        text = '';
    }
}
0

You can store String as a blob in library. It should be easy to create and read it.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .