locked
How to implement a log module for store app?

    Question

  • I am implementing a log module for a win8 store app.

    the basic idea is create a log object during run time and write log via logMessage("str to log") interface to write it in log file, either called from UI thread or backend thread.

    I can make sure the StorageFile is created during runtime and the logMessage code just look like following:

    void
    LogEntity::InternalLogFunction(Platform::String^ logString)    /* IN */
    {
       if(mLogFileHandler){
          Windows::Storage::FileIO::AppendTextAsync(mLogFileHandler, logString);
       }
    }
    

    During my running, I can see only one line or none of  the text been written to the file. But if I add breakpoint on the AppendTextAsync call, I can see many many calls been reached.

    Does this mean an async call can not be re-entered? and what's the proper way to fulfill my purpose?

    I just tried another way to make it a little bit synchronized, but it will cause exception:

          auto t = create_task(Windows::Storage::FileIO::AppendTextAsync(mLogFileHandler, logString));
          t.wait();
    

    Wednesday, June 26, 2013 6:39 AM

Answers

  • Since file I/O operation takes some times, WinRT has made all API asynchronous. If you want to sync them you need to use task chain. As I/O operations are time consuming, it should belongs to a separate worker thread, I suppose.

    You may try like the following code snapped

    HRESULT  taskResult = S_OK;
    
    create_task(FileIO::AppendTextAsync( currentFile, stringToAppend , UnicodeEncoding::Utf8 )).then([&taskResult](task<void> writeTask)
                {
                    try
                    {
                        writeTask.get();         // get exception
                    }
                    catch(COMException^ ex)
                    {
                        taskResult = exception->HResult;
                    }
                }).get();
    
    if (taskResult == S_OK)
    	{
    		return true;
    	}
    else 
            {
                    return false;
            }

    Since UI thread does not allow any kind of blocking, you have to execute it into a separate worker thread.

    Wednesday, June 26, 2013 3:22 PM