diff --git a/app/extend/context.js b/app/extend/context.js index c1c27f9256..313e808905 100644 --- a/app/extend/context.js +++ b/app/extend/context.js @@ -196,8 +196,9 @@ const proto = module.exports = { runInBackground(scope) { const ctx = this; const start = Date.now(); + // try to use custom function name first /* istanbul ignore next */ - const taskName = scope.name || scope._name || eggUtils.getCalleeFromStack(true); + const taskName = scope._name || scope.name || eggUtils.getCalleeFromStack(true); // use app.toAsyncFunction to support both generator function and async function ctx.app.toAsyncFunction(scope)(ctx) .then(() => { diff --git a/test/app/extend/context.test.js b/test/app/extend/context.test.js index cf649762dd..96a2addf72 100644 --- a/test/app/extend/context.test.js +++ b/test/app/extend/context.test.js @@ -250,6 +250,20 @@ describe('test/app/extend/context.test.js', () => { ); }); + it('should use custom task name first', async () => { + await app.httpRequest() + .get('/custom') + .expect(200) + .expect('hello'); + await sleep(5000); + const logdir = app.config.logger.dir; + const log = fs.readFileSync(path.join(logdir, 'ctx-background-web.log'), 'utf8'); + assert(/background run result file size: \d+/.test(log)); + assert( + /\[egg:background] task:customTaskName success \(\d+ms\)/.test(fs.readFileSync(path.join(logdir, 'egg-web.log'), 'utf8')) + ); + }); + it('should run background task error', async () => { mm.consoleLevel('NONE'); await app.httpRequest() diff --git a/test/fixtures/apps/ctx-background/app/controller/custom.js b/test/fixtures/apps/ctx-background/app/controller/custom.js new file mode 100644 index 0000000000..4d8aa4b84a --- /dev/null +++ b/test/fixtures/apps/ctx-background/app/controller/custom.js @@ -0,0 +1,13 @@ +'use strict'; + +const fs = require('mz/fs'); + +module.exports = async ctx => { + ctx.body = 'hello'; + const fn = async function saveUserInfo(ctx) { + const buf = await fs.readFile(__filename); + ctx.logger.warn('background run result file size: %s', buf.length); + }; + fn._name = 'customTaskName'; + ctx.runInBackground(fn); +}; diff --git a/test/fixtures/apps/ctx-background/app/router.js b/test/fixtures/apps/ctx-background/app/router.js index f8a2849bb3..f1d51fe16d 100644 --- a/test/fixtures/apps/ctx-background/app/router.js +++ b/test/fixtures/apps/ctx-background/app/router.js @@ -2,6 +2,7 @@ module.exports = app => { app.get('/', app.controller.home); + app.get('/custom', app.controller.custom); app.get('/app_background', app.controller.app); app.get('/error', app.controller.error); };