Best Practices - Stored Procedure Logging

后端 未结 4 1745
后悔当初
后悔当初 2021-02-07 02:25

If you have a long running SP, do you log somehow its actions or just wait for this message?

\"Command(s) completed successfully.\"

4条回答
  •  孤街浪徒
    2021-02-07 03:03

    In order to see how long things are taking, and how many rows the previous action modified, I add the current date + time and the last row count to every entry. I use this procedure:

    CREATE PROCEDURE dbo.[Log]
        @Message NVARCHAR(512),
        @RowCount INT = null OUTPUT,
        @Delimiter NCHAR(1) = N' ',
        @PadChar NCHAR(1) = N'-'
    AS
        BEGIN
            SET @RowCount = @@ROWCOUNT;
    
            DECLARE @LogDate AS NVARCHAR(50);
            DECLARE @RowCountPadded AS NCHAR(8);
    
            SET @LogDate = CONVERT(NVARCHAR(50),GETDATE(),121);
            SELECT @RowCountPadded = CASE @RowCount WHEN 0 THEN REPLICATE(@PadChar,8) ELSE REPLACE(STR(@RowCount, 8), SPACE(1), @PadChar) END; 
    
            SET @Message = @LogDate + @Delimiter + @RowCountPadded + @Delimiter + @Message;
            RAISERROR (@Message, 0, 1) WITH NOWAIT;
        END
    

    So, in your procedures, add log output like this:

    EXEC dbo.[Log] 'the message';
    

    It produces this:

    2012-12-28 11:28:25.197 -------- the message
    

    Had you performed some action previously, you'd see the row count where the dashes are. If you needed the row count for something else (e.g. to log to a table), you can get it back from the procedure as an OUTPUT parameter.

    UPDATE: Use this gist if you want to create this procedure once and use it everywhere.

    -- removed lines ---

提交回复
热议问题