% SessionLogger Add session logging

% Copyright 2017-2020 The MathWorks, Inc.

classdef SessionLogger < handle
    properties (SetAccess = immutable)
        JavaLoggerObj
        Handler
        Session
        Pool
    end
    methods
        function obj = SessionLogger(session)
            parallel.internal.pool.serializationProfiling('enable');
            if nargin < 1
                % Worker-side constructor.
                session = parallel.internal.pool.workerSession();
                assert(~isempty(session), ...
                       'Session was unexpectedly empty.');
                session = session.Session;
            end
            obj.Session = session;
            obj.JavaLoggerObj = com.mathworks.toolbox.distcomp.pmode.LoggingSessionProfilingListener;
            obj.Handler = parallel.internal.profiling.LoggingSessionHandler(obj.JavaLoggerObj);
            obj.Session.addProfilingListener(obj.JavaLoggerObj);
        end
        function stop(obj)
            % This method is idempotent, so it is safe to call from the destructor too.
            obj.Session.removeProfilingListener(obj.JavaLoggerObj);
        end
        function delete(obj)
            parallel.internal.pool.serializationProfiling('disable');
            stop(obj);
        end
        function tt = drainMessageLog(obj)
            tt = obj.Handler.drainMessageLog();
        end
        function tt = drainMatlabLog(obj)
            tt = obj.Handler.drainMatlabLog();
        end
        function tt = drainDispatchLog(obj)
            tt = obj.Handler.drainDispatchLog();
        end
        function tt = drainLanguageConstructLog(obj)
            tt = obj.Handler.drainLanguageConstructLog();
        end
    end
end
